当道具改变时渲染反应组件
render react component when prop changes
如何在 props 改变时强制渲染我们的组件?
如何在子组件的 props 发生变化时强制渲染父组件?
我搜索了很多,但所有解决方案在新的 React 版本中都已弃用。
在我的任何页面中(路线精确路径=“/post/:id”组件={post})例如(siteUrl/post/1)我得到(:id ) 来自道具 (this.props.match.params) 并且有效。
但是当我在单页组件 (Post) 和这个路由 (siteUrl/post/1) 中时,当我将新的道具传递给这个组件 (:id) 时。
props 会改变但单个组件和父组件不会重新渲染...
要使 parent 和 child re-render 您需要将 prop 从 parent 传递到 child.
// parent using
<Parent someProp={{someVal}} />
// parent render:
render() {
const { someProp } = this.props
<Child someProp={{someProp}} />
}
这肯定会 re-render 两个组件,除非您在 componentShouldUpdate
中声明了另一个逻辑
在你的情况下 Router
看起来像 Parent
的 parent 所以你应该只将路径 :id
作为道具。
确保 Router
位于顶层,就在 App
下方
重要的是,您首先在构造函数中初始化子项的 someVal
public static getDerivedStateFromProps(
nextProps,
nextState
) {
let { someVal } = nextProps;
if (nextState.someVal !== someVal) {
return {
initialVal,
someVal: someVal
};
}
return null;
}
因为状态发生变化,它会在 prop 发生变化后重新渲染
您可能正在使用 componentDidMount 方法。
componentDidMount() is invoked immediately after a component is
mounted (inserted into the tree). Initialization that requires DOM
nodes should go here. If you need to load data from a remote endpoint,
this is a good place to instantiate the network request.
但是你需要使用componentDidUpdate。
componentDidUpdate() is invoked immediately after updating occurs.
This method is not called for the initial render.
您也可以在不编写 class 的情况下使用状态和其他 React 功能。
阅读更多:https://reactjs.org/docs/hooks-effect.html
如何在 props 改变时强制渲染我们的组件? 如何在子组件的 props 发生变化时强制渲染父组件?
我搜索了很多,但所有解决方案在新的 React 版本中都已弃用。
在我的任何页面中(路线精确路径=“/post/:id”组件={post})例如(siteUrl/post/1)我得到(:id ) 来自道具 (this.props.match.params) 并且有效。
但是当我在单页组件 (Post) 和这个路由 (siteUrl/post/1) 中时,当我将新的道具传递给这个组件 (:id) 时。
props 会改变但单个组件和父组件不会重新渲染...
要使 parent 和 child re-render 您需要将 prop 从 parent 传递到 child.
// parent using
<Parent someProp={{someVal}} />
// parent render:
render() {
const { someProp } = this.props
<Child someProp={{someProp}} />
}
这肯定会 re-render 两个组件,除非您在 componentShouldUpdate
在你的情况下 Router
看起来像 Parent
的 parent 所以你应该只将路径 :id
作为道具。
确保 Router
位于顶层,就在 App
重要的是,您首先在构造函数中初始化子项的 someVal
public static getDerivedStateFromProps(
nextProps,
nextState
) {
let { someVal } = nextProps;
if (nextState.someVal !== someVal) {
return {
initialVal,
someVal: someVal
};
}
return null;
}
因为状态发生变化,它会在 prop 发生变化后重新渲染
您可能正在使用 componentDidMount 方法。
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
但是你需要使用componentDidUpdate。
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
您也可以在不编写 class 的情况下使用状态和其他 React 功能。 阅读更多:https://reactjs.org/docs/hooks-effect.html