简体   繁体   English

我通过 Parent.But this.prop 将 msg 从 Child1 传递给 Child2

[英]I am passing msg from Child1 to Child2 via Parent.But this.prop showing values inside render() but not anywhere else in class

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

I am passing msg from Child1 to Child2 via Parent.我通过父母将消息从 Child1 传递给 Child2。 I have updated the Parent state from Child1 and pass that state variable as a Prop in Child2.我已经从 Child1 更新了 Parent state 并将 state 变量作为 Child2 中的 Prop 传递。 Now I am trying to map that this.props.msgfromChild1 to Child2 state but It is not happening and it remain an empty state variable but In the render() this.props.msgfromChild1 has showing the exact passed value.现在我正在尝试 map this.props.msgfromChild1 到 Child2 state 但它没有发生,它仍然是一个空的 state 变量,但在渲染中I am not getting any kind of an error.我没有收到任何错误。

I have also tried componentdidmount to change the state but that doesn't work.我也尝试过 componentdidmount 来更改 state 但这不起作用。

You are getting msgFromChild1 in props, but it's not being updated in state of child2 because the following code,您在道具中获得msgFromChild1 ,但由于以下代码,它没有在 child2 的 state 中更新,

state={
    Child2_msg_State:this.props.msgFromChild1
}

Only sets the initial state of Child2_msg_State , it does not update the state when props change.仅设置 Child2_msg_State 的初始Child2_msg_State ,不会在 props 更改时更新 state。

You were almost right when you tried to use ComponentDidMount but what you need is ComponentDidUpdate , while ComponentDidMount is called only during the first render of the component, ComponentDidUpdate function is called every time a component's data changes, in our case the value of props changes.当您尝试使用ComponentDidMount时几乎是对的,但您需要的是ComponentDidUpdate ,而ComponentDidMount仅在组件的第一次渲染期间被调用, ComponentDidUpdate function 每次组件的数据更改时都会调用,在我们的例子中是 props 的值发生更改。

So, we have to update our state as props when it changes.因此,我们必须在 state 更改时将其更新为道具。 Using the following function in Child2 component:Child2组件中使用以下 function :

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

In the above code, we are updating the Child2_msg_State whenever Child2 component is updated using ComponentDidUpdate() function在上面的代码中,每当使用ComponentDidUpdate() function 更新Child2组件时,我们都会更新Child2_msg_State

Find the same from CodeSandbox below从下面的 CodeSandbox 中找到相同的

编辑 dreamy-kepler-33eev

You should initialize your state in the constructor :您应该在constructor中初始化您的 state :

constructor(props) {
    super(props);
    this.state = {/*initialization*/};
  }

If your component still doesn't change the state, try this:如果您的组件仍然没有改变 state,试试这个:

static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.Child2_msg_State !== nextProps.msgFromChild1)
        this.setState({
            Child2_msg_State: nextProps.msgFromChild1
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM