当状态元素为对象时,避免子组件重新呈现

时间:2019-09-06 08:21:00

标签: reactjs state

子组件状态如下:

interface State {
    data: { x: number; y: string };
}

// initial in constructor
this.state = {
     data: {
         x: 10,
         y: 'sss',
     },
};

setState何时显示:

const { data } = this.state;
data.x += 10;
this.setState({ data });

nextStatethis.state中始终等于shouldComponentUpdate,在shouldComponentUpdate中的控制台日志为:

next: {"data":{"x":20,"y":"sss"}} 
this: {"data":{"x":20,"y":"sss"}}

我只希望在setState之后的子级时渲染子级组件,而不是父级组件。

所以,当父组件渲染时,如何避免子组件重新渲染

here is codesandbox


更新:

find an answer, how to set nested state object:

1 个答案:

答案 0 :(得分:1)

问题是您先突变当前状态,然后将其与下一个状态进行比较。

export default class App extends React.Component {
  state = {
    name: 'hello',
    data: {
      x: 10,
      y: 'sss'
    }
  };

  shouldComponentUpdate(nextProps, nextState) {
    console.log('this', this.state.data.x);
    console.log('next', nextState.data.x);
    const isRender = this.state.data.x !== nextState.data.x; 
    console.log('will render?', isRender);
    return isRender;
  }

  render() {
    const { name, data } = this.state;
    // Dont mutate state
    // data.x += 10;
    return (
      <FlexBox>
        <Input
          value={name}
          onChange={e => this.setState({ name: e.target.value, data: data.x+10 })}
        />
      </FlexBox>
    );
  }
}

Edit Q-57818273-MutateState


在您的沙盒示例中,修复shouldComponentUpdate逻辑:

  shouldComponentUpdate(nextProps, nextState) {
    console.log('In should child update', nextState.data, this.state.data);
    const willRender = nextState.data !== this.state.data;
    console.log('will render?', willRender);
    return willRender;
  }

  changeCurrentState = () => {
    const { data } = this.state;

    // Dont mutate state.
    // data.x += 10;
    // this.setState({ data });
    this.setState({ data: { x: data.x + 10 } });
  };

Edit Q-57818273-ChildNotRenderOnParent