admin管理员组文章数量:1323330
I want to create a Modal-like ponent that receives an open/closed boolean as a prop, then stores that value in the ponent state. When closing the Modal, I want to update the close boolean prop, but wait a few seconds before updating the ponent state so that I can add transition classes and animate the exit.
With ponentWillReceiveProps
, I could acplish this by wrapping this.setState
in a timeout and add the classes in the meantime. With the new React 16.3 API, I see that is is remended to use the getDerivedStateFromProps
instead.
Since getDerivedStateFromProps
"should return an object to update state, or null to indicate that the new props do not require any state updates," (React docs) I want the method to look something like this:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.menuIsOpen === false && prevState.menuIsOpen === true) {
return setTimeout(() => { menuIsOpen: false}, 1000);
}
return null;
}
But that doesn't work. I've read that setTimeout
does not return a value but am wondering if there is a more elegant solution to the problem than returning a promise.
I want to create a Modal-like ponent that receives an open/closed boolean as a prop, then stores that value in the ponent state. When closing the Modal, I want to update the close boolean prop, but wait a few seconds before updating the ponent state so that I can add transition classes and animate the exit.
With ponentWillReceiveProps
, I could acplish this by wrapping this.setState
in a timeout and add the classes in the meantime. With the new React 16.3 API, I see that is is remended to use the getDerivedStateFromProps
instead.
Since getDerivedStateFromProps
"should return an object to update state, or null to indicate that the new props do not require any state updates," (React docs) I want the method to look something like this:
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.menuIsOpen === false && prevState.menuIsOpen === true) {
return setTimeout(() => { menuIsOpen: false}, 1000);
}
return null;
}
But that doesn't work. I've read that setTimeout
does not return a value but am wondering if there is a more elegant solution to the problem than returning a promise.
-
Try doing what you were doing before in
ponentDidUpdate
instead ofponentWillReceiveProps
. – Evan Trimboli Commented May 1, 2018 at 11:10
1 Answer
Reset to default 10You can use ponentDidUpdate
:
ponentDidUpdate(prevProps){
// update your class names...
if (!this.props.menuIsOpen && this.state.menuIsOpen) {
setTimeout(() => this.setState({ menuIsOpen: false}), 1000);
}
}
本文标签: javascriptHow to use React39s getDerivedStateFromProps with a setTimeoutStack Overflow
版权声明:本文标题:javascript - How to use React's getDerivedStateFromProps with a setTimeout? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742141336a2422592.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论