【发布时间】:2019-01-28 04:43:10
【问题描述】:
目标:通过从父级的非状态变量发送道具,仅重新渲染子组件。
我想只重新渲染没有父渲染的子组件。下面是我编写的示例代码。 cRoot 是 parent 传递 props,CButton 子组件需要在 Visibility 变量更改时渲染。
- 在子组件中,我没有使用过 state,因为它曾经是一次,我不想在 state 中保留该值。我也不想将 Child 创建为 Pure 组件。
- 在 parent 中,我想使用变量 (submitBtnVisibility) 作为 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>;
}
}
【问题讨论】:
标签: javascript reactjs