简体   繁体   English

反应setState导致不稳定的数组行为

[英]react setState causing erratic array behaviour

I'm calling my function every 10 seconds. 我每10秒调用一次函数。

setInterval(this.getStudent, 10000);

Within the function it should grab the latest state of the students array. 在函数内,它应获取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 });
}

If I console.log(this.state.students); 如果我console.log(this.state.students); it shows the creation of a student after 10 seconds just fine. 它显示10秒钟后就可以创建一个学生。

Object // After 10 seconds perfect!
   name: Liam Smith
   major: BIO
   ...

But after another 10 seconds (20 seconds total) it should just append one more newly created student. 但是再过10秒钟(总计20秒钟),它应该仅追加一名新创建的学生。 But it attaches an extra so looks like this: 但它附加了一个额外内容,因此如下所示:

[Object, Object, Object]

And then from there the timer gets all messed up and adds new students whenever it wants. 然后计时器从那里弄糟,并在需要时添加新学生。 But why is a react state causing this? 但是为什么反应状态会导致这种情况呢? How can I just simply add a student every 10 seconds? 我怎样才能每10秒简单地增加一个学生?

Ps: I'm calling setInterval within render like so... ps:我像这样在render中调用setInterval。

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

    console.log(this.state.cards);
    return (
      <div>
        ....

render() is called every time the component needs to re-render–like when you add a student. 每当组件需要重新渲染时都会调用render()例如添加学生时。

Each time render() is called you start a new interval timer, eg, each time you update state.students , you render, which starts a new timer, which leads to a new student, which leads to a new render, which leads to a lot of new timers, students, and renders, ad nauseum. 每次调用render() ,您都会启动一个新的间隔计时器,例如,每次您更新state.students ,您都会进行渲染,这将启动一个新计时器,这会导致一个新学生,从而导致一个新的渲染,从而导致很多新的计时器,学生和渲染器,广告素材。

You'd want to start a single timer in something like componentDidMount() , eg, 您想在componentDidMount()类的东西中启动单个计时器,例如,

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

render() {
  return (
    <div>
      ...

(This may not satisfy your real requirements, eg, if you have multiple components relying on the same list of students, this wouldn't be appropriate.) (这可能无法满足您的实际需求,例如,如果您有多个组成部分依赖于同一批学生,则不合适。)

Unrelated, but you're currently directly altering state by pushing onto the state.students array. 无关,但是您当前正在通过推入state.students数组直接更改状态。 This can go unpredictably bad for a variety of reasons–just something to keep in mind as you're moving forward. 由于多种原因,这可能会带来不可预料的坏处-在前进的过程中要牢记一些事情。 Correct modification of state arrays in ReactJS 在ReactJS中正确修改状态数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM