在React的setState中使用setTimeout作为回调函数?

3

代码:

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

当React的setState没有回调函数时,它是可以工作的,但我需要在3秒后将activateLightColorForYellow设置为false。如果我在setTimeout外部使用setState,setState就不能工作。有帮助吗?


移除setState上的回调函数。然后在setTimeout中(父级?)下方,等待3秒钟后它将被评估。对吗?但是setState不起作用。 - gpbaculio
2个回答

2

setState的回调函数可以确保状态已经被改变。
以下是一个使用链式setTimeout的小例子:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      title: "click me"
    };

    this.onClick = this.onClick.bind(this);
  }

  onClick(e) {
    this.setState({ title: "value 1" }, () => {
      setTimeout(() => {
        this.setState({ title: "value 2" }, ()=>{
          setTimeout(()=>{
            this.setState({title: 'value 3'})
          },1500);
        });
      }, 1000);
    });
  }

  render() {
    return (
      <div>
        <div onClick={this.onClick}>{this.state.title}</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


0
我相信你有语法错误。第二个 setTimeout 缺少箭头函数。
请尝试这个;
setTimeout(()=> {
  this.setState((state, props) => ({ activateLightColorForRed: true }), () => {
    setTimeout(()=> {
      this.setState(()=> ({ activateLightColorForRed: false }))
    }, 3000);
    red.play();
  })
}, 3000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接