[英]ReactJs Child Component is not getting updated through Props
目标:通过从父级的非状态变量发送道具,仅重新渲染子级组件。
我只想重新渲染子组件,而无需父渲染。 以下是我编写的示例代码。 cRoot是传递父项的道具,并且需要在更改Visibility变量时呈现CButton Child组件。
您能否解释一下为什么子组件未更新,因为子组件的观点道具正在更新? 还是指着我哪里出问题了?
预先非常感谢您的帮助。
// 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>;
}
}
考虑一下,您的Child组件如何重新渲染? 如果其道具或状态发生变化。 好的,现在考虑一下您的父组件如何将其更改后的prop传递给子组件? 当它当然会退货。
父组件如何重新呈现? 当然,当它的状态改变时(或者是道具,但对于父项,现在没有任何道具)。 因此,您不会更改父级的状态,并且不会重新渲染。 因此,您的孩子不会重新渲染。 就这么简单。
您不能渲染子组件,除非它在父组件之上获得了新的道具。 除非其状态(或道具)发生变化,否则父级不会重新渲染。 在这里,您不执行任何操作。
评论后更新
除非渲染父组件,否则无法渲染子组件。 父母没有变化,孩子就没有重新投降。
不要害怕渲染太多。 渲染本身并不那么昂贵,而DOM更改却很昂贵。 React将DOM(虚拟的和真实的)进行比较,如果没有任何变化,它不会卸载/重新安装组件。
另外,我不知道您为什么不想使用PureComponent
但是它提供了您想要的功能。 除了可以使用shouldComponentUpdate
之外,还可以使用shouldComponentUpdate
,但是大多数人不建议使用它,因为它还有其他缺点,如果使用不当,则会降低性能而不是降低性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.