首页 > 解决方案 > 我通过 Parent.But this.prop 将 msg 从 Child1 传递给 Child2

问题描述

import React, { Component,Fragment } from 'react';
import Child1 from './Child1'
import Child2 from './Child2'

class Parent extends Component{
  state={
    Parent_msg_state:""
  }
  render(){
    
    return(
      <Fragment>
        {JSON.stringify(this.state)}
        <Child1 changePstate={(msg)=>this.setState({Parent_msg_state:msg})}/>
        <Child2 msgFromChild1={this.state.Parent_msg_state}/>
      </Fragment>
    )
  }
}

export default Parent;

This is Parent 


#Child1#
import React, { Component, Fragment } from "react";

class Child1 extends Component {
  render() {
    return (
      <Fragment>
        <table>
          <tr>John</tr>
          <tr>Cena</tr>
          <tr>12</tr>
          <tr>
            <button
              type="button"
              onClick={(data) => this.props.changePstate("Hi Child2")}
            >
              Send msg to child2 via Parent
            </button>
          </tr>
        </table>
      </Fragment>
    );
  }
}

export default Child1;

This is Child1 

#Child2#

import React, { Component,Fragment } from 'react';


class Child2 extends Component{
    state={
        Child2_msg_State:this.props.msgFromChild1 --> Unable to map 
    }
  render(){
    return(
      <Fragment>
          {JSON.stringify(this.state)}
          {JSON.stringify(this.props.msgFromChild1)} -->Msg is reflecting here but not in state
            <h1>{this.props.msgFromChild1}</h1>
      </Fragment>
    )
  }
}

export default Child2;
This is child2

我通过父母将消息从 Child1 传递给 Child2。我已经从 Child1 更新了 Parent 状态,并将该状态变量作为 Child2 中的 Prop 传递。现在我正在尝试将 this.props.msgfromChild1 映射到 Child2 状态,但它没有发生,它仍然是一个空状态变量,但是在 render() this.props.msgfromChild1 中显示了确切的传递值。我没有收到任何错误。

我也尝试过 componentdidmount 来更改状态,但这不起作用。

标签: javascriptreactjs

解决方案


您正在获取msgFromChild1道具,但由于以下代码,它没有在 child2 状态下更新,

state={
    Child2_msg_State:this.props.msgFromChild1
}

只设置 的初始状态Child2_msg_State,不会在 props 变化时更新状态。

当您尝试使用时几乎是对的,ComponentDidMount但您需要的是ComponentDidUpdate,虽然ComponentDidMount仅在组件的第一次渲染期间调用,但ComponentDidUpdate每次组件的数据更改时都会调用函数,在我们的例子中是 props 的值更改。

因此,我们必须在状态发生变化时将其更新为道具。在组件中使用以下函数Child2

componentDidUpdate(prevProps) {
    // Added prevProps conditional check to prevent infinite loop
    if (prevProps.msgFromChild1 !== this.props.msgFromChild1) {
      this.setState({
        Child2_msg_State: this.props.msgFromChild1
      });
    }
  }

在上面的代码中,我们使用函数更新组件更新Child2_msg_StateChild2ComponentDidUpdate()

从下面的 CodeSandbox 中找到相同的

编辑 dreamy-kepler-33eev


推荐阅读