首页 > 解决方案 > 更新道具反应后如何更新组件

问题描述

更新道具后如何更新组件?我有以下组件结构:

MyList.js 
render() {
 return(
  <ComponentList products={props.products}>
  <ComponentBoard product={props.product[i]} //send choosen product(1) from list(100 products)
 )
}

并且下一个组件有 2 个相似的组件 contentRow

ComponentList.js (
same(
 <contentRow > list .map() //100 contentRow
)

ComponentBoard.js
same(
 <contentRow > // 1 contentRow
)

在组件 componentRow 中有一些字段显示并通过 redux 更改存储中的数据,例如用户名。

当我打开 ComponentBoard 组件并更改 ComponentRov 字段中的值时,ComponentList> componentRow 中的值也应该更改。

为了更好地理解:

ComponentList 是一个ComponentRow 的表格,当点击到行时,会打开ComponentBoard 窗口,其中还有一个componentRow。

问题:如何从componentBoard更新componentList中显示的数据?他们有来自 1 家商店的类似道具

标签: javascriptreactjsredux

解决方案


当序列props化为初始状态时,您应该监听变化props并相应地更新state。在基于类的组件中,您componentDidUpdate在功能组件中使用,您可以通过useEffect监听给定的更改来实现相同的结果prop

const Component = ({ foo }) =>{
    const [state, setState] = useState(foo) //initial state

    useEffect(() =>{
        setState(foo) //everytime foo changes update the state
    },[foo])
}

class等效的

class Component extends React.Component{
    state = { foo : this.props.foo } // initial state

    componentDidUpdate(prevProps){
          if(prevProps.foo !== this.props.foo)
              this.setState({ foo : this.props.foo }) //everytime foo changes update the state
    }
}

推荐阅读