在React子组件上使用props更新状态

Ada*_*ite 41 javascript reactjs

我有一个React应用程序,其中父组件的道具传递给子组件,然后道具设置子项的状态.

将更新后的值发送到父组件后,子组件不会使用更新的props更新状态.

如何让它更新子组件的状态?

我的精简代码:

class Parent extends React.Component {
    constructor (props) {
        super(props);
        this.state = {name: ''} 
    }
    componentDidMount () {
        this.setState({name: this.props.data.name});
    }
    handleUpdate (updatedName) {
        this.setState({name: updatedName});
    }
    render () {
        return <Child name={this.state.name} onUpdate={this.handleUpdate.bind(this)} />
    }
}


class Child extends React.Component {
    constructor (props) {
        super(props);
        this.state = {name: ''} 
    }
    componentDidMount () {
        this.setState({name: this.props.name});
    }
    handleChange (e) {
        this.setState({[e.target.name]: e.target.value});
    }
    handleUpdate () {
        // ajax call that updates database with updated name and then on success calls onUpdate(updatedName)
    }
    render () {
        console.log(this.props.name); // after update, this logs the updated name
        console.log(this.state.name); // after update, this logs the initial name until I refresh the brower
        return <div>    
                    {this.state.name}
                    <input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
                    <input type="button" value="Update Name" onClick={this.handleUpdate.bind(this)} />
                </div>
    }
}
Run Code Online (Sandbox Code Playgroud)

Blo*_*ard 63

你需要componentWillReceiveProps在孩子身上实施:

componentWillReceiveProps(newProps) {
    this.setState({name: newProps.name});
}
Run Code Online (Sandbox Code Playgroud)

修改: componentWillReceiveProps现已弃用,将被删除,但上面的文档链接中还有其他建议.

  • 你知道那些时候你只想对随机的SO海报说"我爱你",这是其中一个时代.谢谢善良的人. (7认同)
  • 它已经是2018年,我不知道根据反应官方文档更新这个答案是否会好.[componentWillReceiveProps](https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops)将来会被弃用,他们建议使用类似[componentDidUpdate]的东西(https://reactjs.org/docs/react -component.html#componentdidupdate)而不是. (3认同)

小智 7

调用setState()componentWillReceiveProps不会造成额外的重新渲染.接收道具是一个渲染,如果在componentDidUpdate之类的方法中执行,则this.setState将是另一个渲染.我建议this.state.name !== nextProps.nameshouldComponentUpdate中进行操作,以便始终检查是否有任何更新.

componentWillReceiveProps(nextProps) {
    this.setState({name: nextProps.name});
}

shouldComponentUpdate(nextProps) {
    return this.state.name !== nextProps.name;
}
Run Code Online (Sandbox Code Playgroud)