javascript - 我通过 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 来更改状态,但这不起作用。
解决方案
您正在获取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_State
时Child2
ComponentDidUpdate()
从下面的 CodeSandbox 中找到相同的
推荐阅读
- android - 如何更改已知项目保存在 SharedPrefrence 中并将图标设置为菜单中的收藏夹?
- powerbi - 如果为空则跳过一条记录
- eclipse - 更改scala编译器版本时找不到或加载主类错误
- webpack - 为 localhost 配置 HTTPS 以通过 USB 访问手机上的麦克风
- kdb - 如何在kdb的列名中选择包含点的列
- c - 当我想保护对向量的修改时,如果尝试使用 const 子句,为什么它不起作用?
- javascript - 从 css 模块中排除一个文件并单独生成 webpack 资产
- python-3.x - 假设检验总体和样本平均值
- linux - Splunk 错误:“无法查找 HOME 变量”
- c++ - C++ 你可以有条件地向下转换类指针吗?