javascript - 更新道具反应后如何更新组件
问题描述
更新道具后如何更新组件?我有以下组件结构:
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 家商店的类似道具
解决方案
当序列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
}
}
推荐阅读
- postgresql - 使用可变后连接设置 application_name?
- google-cloud-platform - Stackdriver 跟踪分析报告的请求过滤器中的通配符?
- python-3.x - 为什么我的条码扫描仪没有列为 /dev/ 设备?
- multithreading - 在 Julia 中使用比一个慢的线程
- css - 当容器小于行高时如何垂直对齐文本?
- apache-spark - 等待 HiveServer2 和 Remote Spark Driver 之间的 SASL 协商完成时超时
- java - Java String replace - 非捕获组捕获
- c# - 为什么我的数据重复?(ASP.Net Mvc)
- apache-kafka - 找不到 tombstoneHandler 类
- python - with open() 给出 TypeError: an integer is required (got type str)