Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react setState导致阵列行为不稳定_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript react setState导致阵列行为不稳定

Javascript react setState导致阵列行为不稳定,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我每10秒调用一次函数 setInterval(this.getStudent, 10000); 在函数中,它应该获取students数组的最新状态 getStudent() { const initialArr = this.state.students; const student = createStudent(); // this function works // it just returns a

我每10秒调用一次函数

setInterval(this.getStudent, 10000);
在函数中,它应该获取students数组的最新状态

getStudent() {
   const initialArr = this.state.students;
   const student = createStudent(); // this function works
                                     // it just returns a student object
   initialArr.push(student);
   this.setState({ students: initialArr });
}
如果我
console.log(this.state.students)它显示10秒后创建一个学生的过程

Object // After 10 seconds perfect!
   name: Liam Smith
   major: BIO
   ...
但再过10秒(总共20秒)后,它应该只追加一个新创建的学生。但它附加了一个额外的,所以看起来像这样:

[Object, Object, Object]
从那以后,计时器就变得乱七八糟,随时可以添加新的学生。但为什么反应状态会导致这种情况?我怎么能简单地每10秒添加一个学生

Ps:我在渲染中调用setInterval,就像这样

render() {
    setInterval(this.getStudent, 10000);

    console.log(this.state.cards);
    return (
      <div>
        ....
render(){
setInterval(this.getStudent,10000);
console.log(this.state.cards);
返回(
....
每当组件需要重新渲染时,都会调用
render()
,就像添加学生时一样

每次调用
render()
时,您都会启动一个新的间隔计时器,例如,每次更新
state.students
,您都会进行渲染,这将启动一个新计时器,这将导致一个新的学生,这将导致一个新的渲染,这将导致大量新的计时器、学生和渲染

您可能希望在类似
componentDidMount()
的程序中启动单个计时器,例如

componentDidMount() {
  setInterval(this.getStudent, 10000);
}

render() {
  return (
    <div>
      ...
componentDidMount(){
setInterval(this.getStudent,10000);
}
render(){
返回(
...
(这可能无法满足您的实际需求,例如,如果您有多个组件依赖于同一学生列表,则这将不合适。)


不相关,但您当前正在通过推到
状态来直接更改状态。students
数组。由于各种原因,这可能会变得不可预测的糟糕-这只是在您前进的过程中要记住的一点。

您从何处调用
setInterval
?听起来您调用它的生命周期不合适ethod,因此您可以同时运行多个间隔。我在render()中调用它@DaveNewton updated post