当道具发生变化时,如何强制呈现组件?当子组件的道具更改时,如何强制呈现父组件?
我搜索了很多,但是所有的解决方案都不推荐使用新的React版本。
例如,在我的任意页面(路由确切的path="/post/:id“component={post})中(siteUrl/post/1),我从道具(this.props.match.params)获得(:id),这是可行的。
但是当我在单页组件(Post)和这个路由(siteUrl/post/1)中时,当我将新的道具传递给这个组件(:id)时。
道具会改变,但单一组件和父组件不会重新呈现.
发布于 2019-03-18 07:44:23
您可能正在使用componentDidMount方法。
componentDidMount()在组件挂载后立即调用(插入到树中)。需要DOM节点的初始化应该放在这里。如果需要从远程端点加载数据,这是实例化网络请求的好地方。
但是你需要使用componentDidUpdate。
更新发生后立即调用componentDidUpdate()。对于初始呈现,不调用此方法。
您也可以在不编写类的情况下使用状态和其他响应特性。阅读更多:https://reactjs.org/docs/hooks-effect.html
发布于 2019-03-05 09:33:16
要使父级和子级都重新呈现,您需要从父级到其子级进行路径支持。
// parent using
<Parent someProp={{someVal}} />
// parent render:
render() {
const { someProp } = this.props
<Child someProp={{someProp}} />
}
这肯定会重新呈现这两个组件,除非您在componentShouldUpdate
中说明了另一个逻辑。
在您的例子中,Router
看起来像Parent
的父级,所以您应该只使用路径:id
作为支撑。
确保Router
在最顶层,就在App
下面
发布于 2019-03-05 09:59:41
重要的是,首先在构造函数中初始化子构造函数的someVal。
public static getDerivedStateFromProps(
nextProps,
nextState
) {
let { someVal } = nextProps;
if (nextState.someVal !== someVal) {
return {
initialVal,
someVal: someVal
};
}
return null;
}
之后,由于状态发生变化,所以会更改道具上的更改。
https://stackoverflow.com/questions/54999321
复制相似问题