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.

Share asked May 1, 2018 at 11:04 SeanMcPSeanMcP 2936 silver badges19 bronze badges 1
  • Try doing what you were doing before in ponentDidUpdate instead of ponentWillReceiveProps. – Evan Trimboli Commented May 1, 2018 at 11:10
Add a ment  | 

1 Answer 1

Reset to default 10

You 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