如何在setState之后立即通过setTimeout更改反应状态?

时间:2017-09-11 21:13:45

标签: javascript reactjs

这里有新的反应,不知道在这样的setState回调上执行此操作是否正确?

           setTimeout(()=> {
            this.setState((state, props) => ({ activateLightColorForRed: true }), () => {
              setTimeout(()=> {
                this.setState(()=> ({ activateLightColorForRed: false }))
              }, 500);
              red.play();
            })
          }, toWait); 

或者类似的东西?

 this.setState((state, props) => {
    this.setState((state, props) => {
      activateLightColorForRed: true
    });
    setTimeout(() => { activateLightColorForRed: false },500)
  })

是否更新了setState回调的状态?在我的组件中发生了一些奇怪的事情,它会多次渲染。我不确定,但我认为这是因为我正在做第一个样本?

1 个答案:

答案 0 :(得分:6)

您的问题似乎没有遵循常规反应应用的模式。您应该使用生命周期事件对正在更改的状态做出反应。你不应该做出多个嵌套的,令人困惑的回调(就好像你想做的那样)。

我可能会建议一个更像这样的结构



class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activateLightColorForRed: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    if (this.state.activateLightColorForRed) {
      // when the state is updated (turned red), 
      // a timeout is triggered to switch it back off
      this.turnOffRedTimeout = setTimeout(() => { 
        this.setState(() => ({activateLightColorForRed: false}))
      }, 500);
    }
  }
  componentWillUnmount() {
    // we set the timeout to this.turnOffRedTimeout so that we can
    // clean it up when the component is unmounted.
    // otherwise you could get your app trying to modify the state on an
    // unmounted component, which will throw an error
    clearTimeout(this.turnOffRedTimeout);
  }
  render () {
    // really simply ui to show how it *could* work
    return (
      <div onClick={this.turnLightRed}>
        The light is {this.state.activateLightColorForRed ? "Red" : "Green"}.
        <br /> Click to change!
      </div>
    )
  }
  turnLightRed = () => {
    // this function will turn the light red
    this.setState(() => ({ 
      activateLightColorForRed: true 
    }));
  }
}

ReactDOM.render(
  <Foo name="World" />,
  document.getElementById('container')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="container"></div>
&#13;
&#13;
&#13;

希望有所帮助。