当属性更改时重新渲染React组件

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:

这是两个组件:

父组件 (Parent Component)

class Parent extends React.Component {
  getChilds(){
    let child = [];
    let i = 0;
    for (let keys in this.props.home.data) {
      child[i] = (
        <Child title={keys} data={this.props.home.data[keys]} key={keys} />
      );
      i++;
      if (i === 6) break;
    }

    return Rows;
  }
  render(){
return (
  <div>
     <h1>I am gonna call my child </h1>
    {this.getChilds()}
 </div>
)

子组件 (Child Component)

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 => <GrandSon item={item} />);
  }
  return grandSons;
 }
  render(){
    return (
      <div>
       <h1> I am the child component and I will call my own child </h1>
      {this.getGrandSon()}
    </div>
     )
 }
}

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
  }
}

翻译自: https://www.freecodecamp.org/news/re-render-react-component-when-its-props-changes/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值