Reactjs 避免在状态元素为object时重新渲染子组件
子组件状态,如:Reactjs 避免在状态元素为object时重新渲染子组件,reactjs,state,Reactjs,State,子组件状态,如: interface State { data: { x: number; y: string }; } // initial in constructor this.state = { data: { x: 10, y: 'sss', }, }; 当设置状态时,如: const { data } = this.state; data.x += 10; this.setState({ data }); next
interface State {
data: { x: number; y: string };
}
// initial in constructor
this.state = {
data: {
x: 10,
y: 'sss',
},
};
当设置状态时,如:
const { data } = this.state;
data.x += 10;
this.setState({ data });
nextState
始终等于此状态。在shouldComponentUpdate
中,控制台登录shouldComponentUpdate
为:
next: {"data":{"x":20,"y":"sss"}}
this: {"data":{"x":20,"y":"sss"}}
我希望仅当child在setState
之后时才渲染子组件,而不是父组件渲染
所以,当父组件渲染时,如何避免子组件重新渲染
更新:
问题在于您改变了当前状态,然后将其与下一个状态进行比较
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
-,在这里您的当前状态和下一个状态将是difference@ToanQuocHo抱歉,我写错了函数名和更新问题我猜不出你是如何运行代码及其结构的。这是codesandbox Ok,问题是什么?你没有尝试我的建议我编辑了答案。。你应该更新你的问题
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 } });
};