[英]How to reload child component when the state of parent class changed
in Parent class, I pass the item to child component.在父类中,我将项目传递给子组件。
<InfoWidget bar={this.state.bar}>
</InfoWidget>
then,receive data and use prop.bar
here然后,接收数据并在此处使用
prop.bar
const InfoWidget = (props) =>{
const [length, setLength] = useState([]);
const classes = useStyles();
useEffect(() => {
setLength( props.bar * 10);
}, []);
return(
<Paper>
{length}
</Paper>
);
}
First load it works well, but when the state.bar of parent class changed, child component is not reloaded.第一次加载效果很好,但是当父类的 state.bar 发生变化时,不会重新加载子组件。
I want to reload the child component ,every time the value of parent class changed.我想重新加载子组件,每次父类的值发生变化时。
Where should I change?我应该在哪里改变?
Add it as a dependency:将其添加为依赖项:
useEffect(() => {
setLength(props.bar * 10);
}, [props.bar]);
Add key to parent, when the key
changes it will rerender the component将 key 添加到 parent,当
key
发生变化时,它会重新渲染组件
<InfoWidget key={this.state.bar} bar={this.state.bar}>
</InfoWidget>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.