ReactJS:访问子最终状态

时间:2016-08-16 15:42:57

标签: javascript reactjs

这可能看起来像一个多余的问题但是我在React更新后试图访问React中的孩子的最终状态。我一直在调查React LifeCycle文档(我认为这可能是问题,但不确定),搜索高低,并且无法弄明白。

我有一个组件需要访问子级状态的(最终)值,一旦该子级进行了一些更新(AJAX请求然后执行一些this.setStates)。< / p>

到目前为止,我能够通过ref(Inside componentDidMount)访问该子进程的整个状态,但是当我尝试访问所述状态的特定值时,它返回{ {1}}或null

这里有一些示例代码可供解释(我会尝试尽可能多地使用无用的代码):

undefined

以下是儿童组件供参考(注意:我使用class Layout extends Component { constructor(props) { super(props); } componentDidMount(){ // This gives me the updated State where pageTitle = "Whatever" console.log(this.refs.child1); // However this gives me the initial State where pageTitle = null console.log(this.refs.child1.state.pageTitle); } render(){ return (<div> {React.cloneElement( this.props.children, {ref: 'child1'} )} </div>); } } 表示我的ajax请求):

axios

感谢以这种方式提供的任何帮助

1 个答案:

答案 0 :(得分:1)

要使用回调,请将此代码添加到父元素:

handleAsyncDone(data) {
    // Do whatever it is people do with data
}

然后将该函数传递给子组件,并在子组件中添加

this.props.handleAsyncDone(this.state);

将子状态传递回父级。