我有一个带有链接的“主页”组件,当您单击一个链接时,产品组件将与产品一起加载。我还有另一个组件,它总是可见的,显示“最近访问的产品”的链接。
这些链接在产品页面上不起作用。当我单击链接时,url会更新,并且会进行渲染,但产品组件不会随着新产品的更新而更新。
请参阅此示例:Codesandbox example
以下是index.js中的路由:
<BrowserRouter>
  <div>
    <Route
      exact
      path="/"
      render={props => <Home products={this.state.products} />}
    />
    <Route path="/products/:product" render={props => <Product {...props} />} />
    <Route path="/" render={() => <ProductHistory />} />
    <Link to="/">to Home</Link>
  </div>
</BrowserRouter>;ProductHistory中的链接如下所示:
<Link to={`/products/${product.product_id}`}> {product.name}</Link>所以它们与Route path="/products/:product"相匹配。
当我在产品页面上尝试使用ProductHistory链接时,URL会更新并呈现,但组件数据不会更改。在Codesandbox示例中,您可以在Product components render函数中取消对警报的注释,以查看当您单击链接时它会呈现出来,但没有任何反应。
我不知道是什么问题is...Can你解释了这个问题并找到了解决方案?那太好了!
发布于 2018-01-08 00:44:46
由于Product组件已加载,因此不会重新加载。您必须在component的以下方法中处理新产品id
componentWillReceiveProps(nextProps) {
if(nextProps.match.params.name.product == oldProductId){
  return;
}else {
 //fetchnewProduct and set state to reload
}使用最新版本的react(16.3.0及以上版本)
static getDerivedStateFromProps(nextProps, prevState){
   if(nextProps.productID !== prevState.productID){
     return { productID: nextProps.productID};
  } 
  else {
     return null;
  }
}
componentDidUpdate(prevProps, prevState) {
  if(prevProps.productID !== this.state.productID){
     //fetchnewProduct and set state to reload
  }
}发布于 2019-06-04 08:09:39
虽然上面提到的所有方法都可以工作,但我看不出使用getDerivedStateFromProps有什么意义。基于React文档,“如果你只想在道具改变时重新计算一些数据,那就使用一个memoization helper来代替”。
在这里,我建议简单地使用componentDidUpdate,同时将Component更改为PureComponenet。
关于React文档,PureComponenet只有在至少有一个状态或属性值发生更改时才会重新呈现。更改是通过对状态键和属性键进行浅层比较来确定的。
  componentDidUpdate = (prevProps) => {
    if(this.props.match.params.id !== prevProps.match.params.id ) {
      // fetch the new product based and set it to the state of the component
   };
  };
请注意,仅当您将组件更改为PureComponent时,上述操作才有效,显然,您需要从React导入它。
发布于 2019-03-28 04:01:36
如果您不在组件中维护状态,则可以在不需要getDerivedStateFromProps的情况下使用componentDidUpdate
  componentDidUpdate(prevProps) {
    const { match: { params: { value } } } = this.props
    if (prevProps.match.params.value !== value){
      doSomething(this.props.match.params.value)
    }
  }https://stackoverflow.com/questions/48139281
复制相似问题