简体   繁体   English

父类状态改变时如何重新加载子组件

[英]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.

相关问题 更改父状态时如何防止子组件重新加载 - how to prevent child component from reload when the parent state is change 更改父状态后如何重新呈现子组件? - How to re-render child component when Parent state is changed? React:在子组件中更改了 state。 如何查看父组件的变化? - React: Changed state in Child component. How to see the change in parent component? 通过子组件更改父状态时,React重新渲染 - React Re-renders When Parent State is Changed Through Child Component 通过父组件过滤子组件时如何维护子组件的state? - How to maintain state of child components when they are filtered through the parent component? 如何在父组件中使用子组件的状态? - How to use the state of the child component in the parent component? 一旦 state 或数据在反应 class 使用组件确实安装后如何重新加载页面 - How to reload page once state or data is changed within a react class using component did mount 更改 state 时如何重新渲染反应 class 组件 - How to re-rendering react class component when state is changed 当父组件中发生事件时,如何从子组件更新父组件中的 state - How do you update state in parent component from a child component when an event takes place in the parent component 父组件状态改变,子组件不重新渲染 - State changed in parent component, child components do not re-render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM