简体   繁体   English

ComponentDidMount 本地状态更新

[英]ComponentDidMount local state update

I have someId that I am getting trough the props and I have otherId in the state.我有someId我正在通过道具的someId ,我在状态中有其他otherId Doing this causes infinite loop.这样做会导致无限循环。 I want that if it is the same id to setState , if it's not to do nothing.如果它与setState id 相同,我希望它不是什么都不做。 How can I achieve this?我怎样才能做到这一点?

 componentDidUpdate(prevProps, prevState) {
         if (prevProps.someId === this.state.otherId) {
             this.setState({ ... });
         }
    }
componentDidUpdate(props) {
     if (props.someId !== this.state.otherId) {
             this.setState({ otherId: props.someId });
     }
}

I assume you meant to say: I want that if props.someId is the same as this.state.someId do nothing, if it's not, set it to it...?我假设您的意思是:我希望如果 props.someId 与 this.state.someId 相同,则什么都不做,如果不是,请将其设置为...? Or if you want them to be different then just change !== back to === .或者,如果您希望它们不同,那么只需将!==改回===

My guess is that since you call setState , the component will update again, thus calling the function again endlessly.我的猜测是,由于您调用setState ,组件将再次更新,从而无休止地再次调用该函数。

Maybe you should use shouldComponentUpdate() instead.也许你应该使用shouldComponentUpdate()来代替。

shouldComponentUpdate(nextProps, nextState) {
    return this.props.someId === nextProps.otherId
}

This way, the component will update only if the ids are the same.这样,只有当 id 相同时,组件才会更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM