子组件状态如下:
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 });
nextState
在this.state
中始终等于shouldComponentUpdate
,在shouldComponentUpdate
中的控制台日志为:
next: {"data":{"x":20,"y":"sss"}}
this: {"data":{"x":20,"y":"sss"}}
我只希望在setState
之后的子级时渲染子级组件,而不是父级组件。
所以,当父组件渲染时,如何避免子组件重新渲染
更新:
答案 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>
);
}
}
在您的沙盒示例中,修复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 } });
};