简体   繁体   English

关于生命周期方法和渲染反应?

[英]About life cycle methods and render in react?

My question is about life cycle methods in react, now i have this scenario: Some data are fetched by ajax in componentDidMount in the parent component and then this data passed as a prop to as the child component, now we are in the child so we can implement different life cycle methods,我的问题是关于react中的生命周期方法,现在我有这个场景:父组件的componentDidMount中的ajax获取一些数据,然后这些数据作为prop传递给子组件,现在我们在子组件中,所以我们可以实现不同的生命周期方法,

componentDidMount : can not see the true value of the prop for example logging date in it returns empty array instead of the desired array componentDidMount :无法看到道具的真实值,例如在其中记录日期返回空数组而不是所需的数组

componentWillMount : the same. componentWillMount :相同。

componentWillReceiveProps : the same if not use nextProps componentWillReceiveProps : 如果不使用nextProps则相同

componentDidUpdate : logging data returns the desired data passed as prop componentDidUpdate :记录数据返回作为 prop 传递的所需数据

render : returns the desired data渲染:返回所需的数据

So should i always be forced to call my data in componentDidUpdate or render???, Is there a way to manage that without redux??那么我是否应该总是被迫在 componentDidUpdate 或 render 中调用我的数据???,有没有办法在没有 redux 的情况下进行管理?

Your child's componentWillMount and componentDidMount may only be receiving an empty array (I assume this is a default) because the Child component is instantiated before the API result is returned eg <Child result={result} /> as opposed to result.length > 0 && <Child result={result} /> .您孩子的componentWillMountcomponentDidMount可能只接收一个空数组(我认为这是默认值),因为 Child 组件在返回 API 结果之前实例化,例如<Child result={result} />而不是result.length > 0 && <Child result={result} /> Mount only happens once and then componentDidUpdate happens after for every prop change. Mount 只发生一次,然后componentDidUpdate发生在每次 prop 更改之后。

Assuming that you are just displaying the data passed down, it is perfectly acceptable to handle it in render.假设您只是显示传递下来的数据,那么在渲染中处理它是完全可以接受的。 Otherwise if you want to perform additional side-effects then check for it's completeness in the parent component (above paragraph) at which point you should be able to see the full value in the child's componentDidMount .否则,如果您想执行其他副作用,请检查父组件中的完整性(上段),此时您应该能够看到子componentDidMountcomponentDidMount的完整值。 Alternatively you can perform the completeness check in the child's componentDidUpdate as you suggest and handle it there instead.或者,您可以按照您的建议在子componentDidUpdatecomponentDidUpdate执行完整性检查并在那里处理它。

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

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