繁体   English   中英

组件的多个导航链接使用 reactjs 渲染每次点击

[英]multiple nav link for a component render each click using reactjs

我在如何在多个导航链接中呈现相同组件的路线中遇到问题。

我有 2 个这样的导航链接。 当我点击编辑产品时,组件成功渲染细节。 之后,我单击添加产品,然后组件不会再次呈现,因为组件已在编辑产品链接上呈现。

我使用相同的组件进行添加和编辑。

任何人都可以告诉我如何在下次单击时重新渲染该组件。?

提前致谢

          <Route
            path="/addproduct"
            render={() => {
              return userData.is_superuser === true ? (
                <Product />
              ) : (
                <Redirect to="/dashboard" />
              );
            }}
          />
        <Route path="/editproduct/:id" component={Product} />

尝试使用渲染属性如下

<Route path="/editproduct/:id" render={() => <Product/> } />

您是否使用 Switch 组件包装了您的路线?

只是一个额外的信息,你应该看看 react lazy/suspense ,用于代码拆分,对于减少 SPA 加载时间很有用。

我找到了解决这个问题的方法。

您需要在组件中使用componentWillReceiveProps函数。

通过调用 url 第一次点击链接 www.example.com/content1/ componentDidMount() 运行。

现在,当您单击另一个链接时,说 www.example.com/content2/ 调用了相同的组件,但这次 prop 发生了变化,您可以在 componentWillReceiveProps(nextProps) 下访问这个新的 prop,您可以使用它来调用 API 或将状态设为空白并获取新的数据。

componentWillReceiveProps(nextProps){
     //call your API and update state with new props
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM