目标:通过从父组件的非状态变量发送props,仅重新渲染子组件。
我想仅重新渲染子组件而不重新渲染父组件。以下是我编写的示例代码。cRoot是传递props的父组件,CButton子组件需要在Visibility变量更改时进行渲染。
- 在子组件中,我没有使用state,因为它只会发生一次,我不想将该值保留在state中。同时,我也不想将Child创建为Pure组件。
- 在父组件中,我想使用变量(submitBtnVisibility)作为props发送。
请问为什么子组件没有更新?从子组件的角度来看,props已经更新了吗?或者请指出我哪里做错了?
非常感谢您的帮助。
// Parent Component
class Root extends React.Component {
constructor(props) {
super(props);
this.state = { refresh: true };
// Parents non-state variable.
this.submitBtnVisibility = { visibility1: 1, visibility2: 2 };
}
componentDidMount() {
console.log("Root componentDidMount ");
}
componentDidUpdate(prevProps, prevState) {
console.log("Root componentDidUpdate ", prevProps, prevState);
}
handleonclick = () => {
console.log(" Root Btn Clicked");
//this.setState({ var1: 5 }); -> If I enable this line , child is getting rendered
this.submitBtnVisibility.visibility1 = 5;
};
render() {
console.log(" Root Render ");
return (
<div className={classes.uploadContainerArea}>
<Btncomponent visibility={this.submitBtnVisibility} />
<button className={classes.btnroot} onClick={this.handleonclick}>
{" "}
Root Btn{" "}
</button>
</div>
);
}
}
// Child Component
class Btncomponent extends React.Component {
constructor(props) {
super(props);
this.state = { Btnprops: this.props.visibility };
}
componentDidMount() {
console.log("Btncomponent componentDidMount ");
}
componentDidUpdate(prevProps, prevState) {
console.log("Btncomponent componentDidUpdate ", prevProps, prevState);
}
static getDerivedStateFromProps(props, state) {
console.log(" getDerivedStateFromProps ");
return null;
}
shouldComponentUpdate(nextProps, nextState) {
console.log(" shouldComponentUpdate ");
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log(" getSnapshotBeforeUpdate ");
return null;
}
render() {
console.log(" Btncomponent Render ", this.props);
return <button type="button"> {this.props.visibility.visibility1} </button>;
}
}