本文共 2174 字,大约阅读时间需要 7 分钟。
Imagine you have a React and Redux project with two components, a parent and a child.
假设您有一个具有两个组件的React和Redux项目,一个父级和一个子级。
The parent component passes some props to the child component. When the child component receives those props, it should call some Redux action which changes some of the props that were passed from the parent asynchronously.
父组件将一些道具传递给子组件。 当子组件接收到这些道具时,它应该调用Redux操作,该操作会更改从父级异步传递的一些道具。
Here are the two components:
这是两个组件:
class Parent extends React.Component { getChilds(){ let child = []; let i = 0; for (let keys in this.props.home.data) { child[i] = (); i++; if (i === 6) break; } return Rows; } render(){return ( )I am gonna call my child
{this.getChilds()}
class Child extends React.Component { componentDidMount(){ if(this.props.data.items.length === 0){ // calling an action to fill this.props.data.items array with data this.props.getData(this.props.data.id); } } getGrandSon(){ let grandSons = []; if(this.props.data.items.length > 0){ grandSons = this.props.data.items.map( item =>); } return grandSons; } render(){ return ( ) }}I am the child component and I will call my own child
{this.getGrandSon()}
The redux-store
is updated properly, but the child component doesn't re-render.
redux-store
已正确更新,但子组件未重新呈现。
It's normally not the responsibility of the Child
to fill the data. Instead, it should receive data that's already been prepared by the Parent
. Also, props are automatically updated.
填写数据通常不是Child
的责任。 相反,它应该接收Parent
已经准备好的数据。 此外,道具会自动更新。
Still, it can be useful to update and manipulate data from a Child
component, especially when Redux is involved.
尽管如此,更新和处理Child
组件中的数据仍然很有用,尤其是在涉及Redux时。
React is probably performs shallow comparisons, and might not re-render even though the state is clearly changing.
React可能会执行浅层比较,即使状态明显改变,它也可能不会重新呈现。
As a workaround, you can do this in mapStateToProps
:
解决方法是,可以在mapStateToProps
执行以下mapStateToProps
:
const mapStateToProps = state => { return { id: state.data.id, items: state.data.items }}
翻译自:
转载地址:http://vtzzd.baihongyu.com/