2016-08-25 33 views
11

我有一个React应用程序,其中来自父组件的道具被传递给子组件,然后道具设置子组件的状态。使用React子组件上的道具更新状态

将更新后的值发送给父组件后,子组件未更新具有更新的道具的状态。

如何获取它来更新子组件上的状态?

我的削减的代码:

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> 
    } 
} 

回答

31

你需要实现你的孩子componentWillReceiveProps

componentWillReceiveProps(newProps) { 
    this.setState({name: newProps.name}); 
} 
+3

你知道那些你只想说“我爱你”的随机SO海报,这是其中的一次。谢谢你仁慈的人。 – markau

+0

整天都在找这个!试图将状态更新为孩子,并且这样做了 – William

2

这也将是很好的检查,如果你甚至需要更新的状态,因为这会导致重新渲染。

componentWillReceiveProps(newProps) { 
    if (this.state.name !== newProps.name) { 
    this.setState({name: newProps.name}); 
    } 
} 
4

拨打componentWillReceivePropssetState()不会造成额外的重新渲染。接收道具是一个渲染器,如果这个渲染是在像componentDidUpdate这样的方法中执行的,this.setState将是另一个渲染器。我建议在shouldComponentUpdate中执行this.state.name !== nextProps.name,以便检查是否有更新。

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

shouldComponentUpdate(nextProps) { 
    return this.state.name !== nextProps.name; 
} 
相关问题