Updating state with props on React child component

后端 未结 4 817
一向
一向 2021-02-01 01:12

I have a React app, where props from a parent component are passed to a child component and the props then set the state on the child.

After I send an updated value to t

4条回答
  •  臣服心动
    2021-02-01 02:01

    Calling setState() in componentWillReceiveProps doesn't cause additional re-render. Receiving props is one render and this.setState would be another render if that were executed within a method like componentDidUpdate. I would recommend doing the this.state.name !== nextProps.name in shouldComponentUpdate so it's always checked for any update.

    componentWillReceiveProps(nextProps) {
        this.setState({name: nextProps.name});
    }
    
    shouldComponentUpdate(nextProps) {
        return this.state.name !== nextProps.name;
    }
    

提交回复
热议问题