reactjs - 在反应中从父级访问子级的更新状态值
问题描述
我有一个组件“Checkin”,它还包括一个子组件“CheckinGraph”。签入图组件具有三个初始化为 0 的状态值,但在 ComponentDidMount 生命周期中,它们的值从 0 变为特定值。我想从父组件访问这些状态变量。
这是我访问这些状态变量的代码。
子组件
class CheckinGraph extends React.PureComponent{
constructor(props)
{
super(props)
this.state={
totalMaleCount:0,
totalFemaleCount:0,
totalUnspecifiedCount:0
}
}
//Callback function for parent
getCount=()=>
{
let { totalMaleCount, totalFemaleCount, totalUnspecifiedCount}=this.state;
let arr=[totalCount,totalMaleCount,totalFemaleCount, totalUnspecifiedCount];
return arr;
}
componentDidMount()
{
this.setState({totalMaleCount:res.data.maleListCount}); //data is coming from API
this.setState({totalFemaleCount:res.data.femaleListCount});
this.setState({totalUnspecifiedCount:res.data.notSpecified});
}
}
父组件
class CheckIn extends React.Component{
constructor(props)
{
this.state={}
this.graph=React.createRef();
}
componentDidMount()
{
let total=this.graph.current.getCount();
console.log(total);
}
render()
{
return(
<div>
<CheckinGraph ref={this.graph} />
</div>
)
}
}
现在的问题是,我能够访问从子到父的值,但它是初始值,而不是更新的值。知道我做错了什么吗?
解决方案
两种方法:
使用 Redux 管理状态,然后从 CHild 组件派发一个动作
将 onChange 函数传递给子组件,并且每当更新值以从子组件调用该函数。onChange 函数是您可以访问更新值的地方,然后您可以在 Parent 中做任何您想做的事情。
推荐阅读
- visual-studio-2010 - CListCtrl 的 EnableWindow(FALSE) 不会改变它的外观
- c# - 通过 C# 从 Access 中提取 VBA 代码
- opc - 与 Milo OPC Client 连接时 PLC 拒绝连接
- python - 在 Python 中使用 ctypes 实现 NtCreateNamedPipeFile
- python - @api.depends 非存储字段不起作用
- sapui5 - 绑定northwind odata服务到ui5?
- ios - 将 Swift 自定义框架与 Cordova 插件集成
- php - 用php编辑/更新行不起作用/未定义的变量
- layout - 如何在 vaadin 水平布局上重叠两个组件。
- vba - 在连接单元格的情况下按字母顺序对列进行排序