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

标签 javascript reactjs react-router react-router-v4 react-router-dom

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

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

看这个例子: 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 示例中,您可以取消注释产品组件呈现函数中的警报,以查看当您点击链接时它会呈现,但什么也没有发生。

我不知道问题是什么...你能解释一下问题并找到解决方案吗?那太好了!

最佳答案

除了 componentDidMount 之外,您还需要在 Products 中实现 componentWillReceiveProps 或使用 getDerivedStateFromProps(从 v16.3.0 开始) 页面,因为当您更改路由参数时,相同的组件会使用更新的 params 进行重新渲染,并且不会重新安装,因此是因为参数作为 props 传递给组件,并且在 props 更改时,React 组件会重新渲染而不是重新安装。

编辑:从 v16.3.0 使用 getDerivedStateFromProps基于 props 设置/更新状态(无需在两个不同的生命周期方法中指定)

static getDerivedStateFromProps(nextProps, prevState) {
   if (nextProps.match.params.product !== prevState.currentProductId){
      const currentProductId = nextProps.match.params.product
      const result = productlist.products.filter(obj => {

        return obj.id === currentProductId;

      })
     return {

        product: result[0],
        currentId: currentProductId,
        result

      }
  }
  return null;
}

在 v16.3.0 之前,您将使用 componentWillReceiveProps

componentWillReceiveProps(nextProps) {
    if (nextProps.match.params.product !== this.props.match.params.product) {
      const currentProductId = nextProps.match.params.product
      const result = productlist.products.filter(obj => {

        return obj.id === currentProductId;

      })
      this.setState({

        product: result[0],
        currentId: currentProductId,
        result

      })
    }
  }

<强> Working codesandbox

关于javascript - React 不会在路由参数更改或查询更改时重新加载组件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48139281/

相关文章:

javascript - 强制重新加载 JavaScript

javascript - 在 last/之后添加到 URL

javascript - 并发是 JavaScript 语言的一个特性吗?

javascript - 长数组列表渲染使 Angular.js 中的页面滚动变慢

javascript - 使用渲染时卸载 React-router v4

reactjs - react + Electron : components from deps aren't laying out properly

javascript - React 组件在 React bootstrap Navbar 下渲染

javascript - React 中 JSX 的评​​估顺序是什么?

reactjs - 如何从查询字符串中获取参数值?

javascript - JSX 中的条件链接