我只想重新渲染子组件而没有父渲染。以下是我编写的示例代码。 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>;
}
}
答案 0 :(得分:3)
考虑一下,您的Child组件如何重新渲染?如果其道具或状态发生变化。好的,现在考虑一下您的父组件如何将其更改后的prop传递给子组件?当它当然会退货。
父组件如何重新呈现?当然,当它的状态改变时(或者是道具,但对于父项,现在没有任何道具)。因此,您不会更改父级的状态,并且不会重新渲染。因此,您的孩子不会重新渲染。就这么简单。
除非子组件获得了高于父组件的新道具,否则无法渲染子组件。除非其状态(或道具)发生变化,否则父级不会重新渲染。在这里,您什么都不做。
评论后更新
除非渲染父级组件,否则无法渲染子级。父母没有变化,孩子也没有重新投降。
不要害怕渲染太多。渲染本身并不那么昂贵,而DOM更改却很昂贵。 React将DOM(虚拟的和真实的)进行比较,如果没有任何更改,则不会卸载/重新安装组件。
此外,我不知道您为什么不想使用K=4
M=2
du = 0.01
#For m=M
def F(u):
return 1/(1+u)**(K-M+2)
#For m=1,2,...,M-1
def f(u):
return 1/((1+u))**2
#Recursive function to evaluate the integral
def G(h, m, prev_lim):
#print(f'h is {h}, and k is {k}')
if m == M:
res = F(h)
else:
res = 0
u = prev_lim
while u < h:
res += G(h-u, m+1, u)*f(u)*du
u += du
return (math.factorial(K)/math.factorial(K-M))*res
print(G(2, 1, 0))
,但是它提供了您想要的功能。除此之外,您可以使用PureComponent
,但是大多数人不建议使用它,因为它还有其他缺点,如果使用不当,则会降低性能,而不是降低性能。