gpt4 book ai didi

javascript - 如何在 setState 之后通过 setTimeout 立即更改 react 状态?

转载 作者:行者123 更新时间:2023-12-03 13:33:55 24 4
gpt4 key购买 nike

这里是新的react,不知道这样在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 回调上的状态是否已更新?我的组件中发生了一些奇怪的事情,它渲染了多次。我不确定,但我认为这是因为我正在做第一个样本?

最佳答案

您的问题似乎不遵循常规 react 应用程序的模式。您应该使用生命周期事件来对正在更改的状态使用react。您不应该进行多个嵌套的、令人困惑的回调(就像您想要做的那样)。

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

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')
);
<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>

希望有帮助。

关于javascript - 如何在 setState 之后通过 setTimeout 立即更改 react 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46164460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com