我有一个带有链接的"主页"组件,当你点击一个链接时,产品组件将与产品一起加载.我还有一个始终可见的组件,显示"最近访问的产品"的链接.

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

看这个例子:

以下是索引中的路由.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".

当我在产品页面上try 跟踪ProductHistory链接时,URL会更新并呈现,但组件数据不会更改.在Codesandbox示例中,您可以取消对Product components render函数中的alert 的注释,以查看它在跟随链接时的渲染情况,但什么也没有发生.

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

推荐答案

除了componentDidMount,您还需要在Products页中实现componentWillReceiveProps或使用getDerivedStateFromProps(从v16.3.0开始),因为当您更改路由参数时,相同的组件是re-rendered,更新了paramsnot re-mounted,这是因为参数作为props 传递给组件,并且在props 更改时,React组件重新呈现,而不是重新安装.

v16的EDIT:.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

      })
    }
  }

100

Reactjs相关问答推荐

过滤对象数组并通过迭代对象数组将属性放入新数组

为什么我的标签在Redux API中不能正常工作?

如何通过浏览器路由在单独的.jsx文件中使用MUI抽屉?

面对动画警告:未指定`useNativeDriver`.这是必需的选项,并且必须在REACT本机中显式设置为`true`或`False`

Google Firestore无法读取图像-react

如何在REACTIVE js中动态添加或删除输入字段?

如何在中间件中获取 nextAuth 会话

生产部署:控制台中 Firebase 无效 api 密钥错误

列表中的每个子项都应该有一个唯一的keyprops .在react 应用程序中

MERN,将动态列表中的元素插入数组

如何管理组件列表的复杂状态? (Nextjs/ReactJS)

BrowserRouter改变了URL但没有链接到页面

如何在Next.js应用程序中为路由[slug]生成.html文件?

Cypress 组件测试不渲染react 组件(但它的内容)

Material UI v5.11 - Prop sx 在响应式中写了两次

Redux,状态未定义

导入样式化组件时未导入组件内容

无法读取未定义的react native 的属性参数

谁能根据经验提供有关 useEffect 挂钩的更多信息

Cypress 中的 process.env 空对象