【问题标题】:Is there any signal that parent component's state set and then child component's state set too?是否有任何信号表明父组件的状态集然后子组件的状态集?
【发布时间】:2020-04-25 18:19:21
【问题描述】:

当父组件设置状态(itemSelected:item)我也想要子组件设置状态(isShowForm:true),那么有什么信号或条件让我做那件事吗?

<pre>
//this is child Component
class HeaderComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowForm: false,
    };
  }

  handleEdit = () =>{
    if(any signal?){
      this.setState({isShowForm:true})
    }
  }
export default HeaderComponent;

//this is parent Component 
class Task extends Component {
  constructor(props){
    super(props);
    this.state = {
      itemSelected: null,
    }
  }
handleEdit = (item) => {
    this.setState({itemSelected: item})
  }
render() {

    let {itemSelected} = this.state;
return(
 HeaderComponent itemSelected={itemSelected}/>
)

</pre>

【问题讨论】:

    标签: reactjs asynchronous components setstate


    【解决方案1】:

    您可以将所需的状态从父组件传递给子组件,并在子组件中使用componentDidUpdate 生命周期来监听道具并做出相应的反应。

    class HeaderComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isShowForm: false,
        };
      }
    
      componentDidUpdate(prevProps) =>{
        // Any identifying property to see if the itemSelected object has indeed changed. I'm just assuming that it has a unique ID
        if(prevProps.itemSelected && prevProps.itemSelected.id !== this.props.itemSelected.id) {
          this.setState({ isShowForm: true })
        }
      }
    export default HeaderComponent;
    
    //this is parent Component 
    class Task extends Component {
      constructor(props){
        super(props);
        this.state = {
          itemSelected: null,
        }
      }
    handleEdit = (item) => {
        this.setState({itemSelected: item})
      }
    render() {
    
        let {itemSelected} = this.state;
    return(
     <HeaderComponent itemSelected={itemSelected}/>
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-05
      • 2017-05-18
      • 2019-08-19
      • 1970-01-01
      • 2022-12-12
      • 2017-07-10
      • 1970-01-01
      • 2020-12-14
      相关资源
      最近更新 更多