首页 > 解决方案 > 在反应中从父级访问子级的更新状态值

问题描述

我有一个组件“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>
)
}
}

现在的问题是,我能够访问从子到父的值,但它是初始值,而不是更新的值。知道我做错了什么吗?

标签: reactjstypescriptreact-state-managementreact-lifecycle

解决方案


两种方法:

  1. 使用 Redux 管理状态,然后从 CHild 组件派发一个动作

  2. 将 onChange 函数传递给子组件,并且每当更新值以从子组件调用该函数。onChange 函数是您可以访问更新值的地方,然后您可以在 Parent 中做任何您想做的事情。


推荐阅读