是否有任何信号表明父组件的状态已设置,然后子组件的状态也已设置?

Is there any signal that parent component's state set and then child component's state set too?

当父组件设置 state(itemSelected: item) 时,我也希望子组件设置 state(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>

您可以将所需的状态从父组件传递给子组件,并在子组件中使用 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}/>
)