React不会在路线参数更改或查询更改时重新加载组件数据

我有一个带有链接的“主页”组件,当您单击链接时,产品组件就会随产品一起加载。我还有另一个始终可见的组件,其中显示了“最近访问过的产品”的链接。


在产品页面上时,这些链接不起作用。当我单击链接时,URL会更新,并且会进行渲染,但是产品组件不会随新产品一起更新。


请参见以下示例: Codesandbox示例


以下是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示例中,您可以取消注释“产品组件渲染”功能中的警报,以查看您在跟踪链接时呈现的警报,但没有任何反应。


我不知道问题是什么...您能解释问题并找到解决方案吗?那很好啊!


慕村9548890
浏览 888回答 3
3回答

蛊毒传说

由于产品组件已经加载,因此不会重新加载。您必须使用以下组件方法处理新产品IDcomponentWillReceiveProps(nextProps) {if(nextProps.match.params.name.product == oldProductId){&nbsp; return;}else {&nbsp;//fetchnewProduct and set state to reload}使用最新版本的react(16.3.0起)static getDerivedStateFromProps(nextProps, prevState){&nbsp; &nbsp;if(nextProps.productID !== prevState.productID){&nbsp; &nbsp; &nbsp;return { productID: nextProps.productID};&nbsp; }&nbsp;&nbsp; else {&nbsp; &nbsp; &nbsp;return null;&nbsp; }}componentDidUpdate(prevProps, prevState) {&nbsp; if(prevProps.productID !== this.state.productID){&nbsp; &nbsp; &nbsp;//fetchnewProduct and set state to reload&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP