如何使用setInterval()更改某个组件的状态?

时间:2016-03-07 16:51:25

标签: reactjs

我怎样才能让我的状态每2秒随机变化一次?现在它在控制台日志中更改,但它不会呈现它。 活动状态更改应该可视地更改 Switch 组件。例如,如果我排除boxList[0].machines[0].switches[0].active = true它会正确更改,但是当它在 setInterval()中时,它不会改变任何内容。

示例:

App.js

var boxList= [
     {id: 1, machines:[
         {id: 1, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 2, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 3, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 4, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
     ]},
     {id: 2, machines:[
         {id: 1, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 2, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 3, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
         {id: 4, switches:[{id: 1, active: false}, {id: 2, active: false}, {id: 3, active: false}, {id: 4, active: false}]},
     ]},
]}];

class App extends React.Component {
      render() {

    setInterval(() => {
           var x = [0,1].sample()
           var x = [0,1].sample()
           var z = [0,1,2,3].sample()
           var info = [true, false].sample()
           boxList[x].machines[y].switches[z].active = info;
         }, 2000);

    var boxes = boxList.map((box) =>
               <Box key={box.id} box_id={box.id} machines={box.machines} />);

        return (
          <div>
          {boxes}
          </div>
        );
      }
    }

1 个答案:

答案 0 :(得分:1)

您的组件没有状态,它访问一些全局可用的数据。但是,实际问题是您永远不会告诉组件重新渲染。该组件不知道数据已更改,因此无法更新。

如果您不想将数据移动到组件的状态,可以使用forceUpdate强制重新呈现。

但是:render方法永远不应该直接或间接地进行另一个渲染。在setInterval中进行render调用也没有多大意义,因为每次组件渲染时都会创建一个新的区间。

相反,请使用lifecycle methods并在安装组件后创建间隔。不要忘记在组件被销毁时清除间隔!

class App extends React.Component {

  componentDidMount() {
    this._interval = setInterval(() => {
      // ...
      this.forceUpdate();
    }, 2000);
  }

  componentWillUnmount() {
    clearInterval(this._interval);
  }

  render() {
    // ...
  }

}