在 url 更改时,我想重新呈现我的组件我应该怎么做 [英] On url change i want to re render my component how should i do that

查看:25
本文介绍了在 url 更改时,我想重新呈现我的组件我应该怎么做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个获取示例组件的链接,但是当我点击其中任何一个链接时,它会被加载,当我点击另一个链接时,它不会重新渲染,只有 url 被更改.我想在两个链接上重新渲染组件点击.有没有办法做到这一点??

i have two links which fetches the sample component but when i click on any one of them it gets loaded and when i click on another one it wont re render only url gets changed.I want to re render the component on both link clicks .Is there any way to do that??

推荐答案

我曾经在做 React 项目时遇到过类似的问题.

I was facing similar issue sometime back when I was working on a react project.

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

You need to use componentWillReceiveProps function in your component.

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

更新

对于 React 16.3+ 版本,请使用 componentDidUpdate

For react version 16.3+ please use componentDidUpdate

componentDidUpdate (prevProps, prevState) {
  // update state 
}

通过调用 url www.example.com/content/a componentDidMount() 运行,以便在您的组件首次加载时更清楚.

To make it more clear when your component loads for the first time by calling url www.example.com/content/a componentDidMount() is run.

现在,当您单击另一个链接时,说 www.example.com/content/b 调用了相同的组件,但这次 prop 发生了变化,您可以在 componentWillReceiveProps(nextProps) 下访问这个新的 prop,您可以用于调用api并获取新数据.

Now when you click another link say www.example.com/content/b same component is called but this time prop changes and you can access this new prop under componentWillReceiveProps(nextProps) which you can use to call api and get new data.

现在你可以保留一个通用函数,比如 initializeComponent() 并从 componentDidMount()componentWillReceiveProps()

Now you can keep a common function say initializeComponent() and call it from componentDidMount() and componentWillReceiveProps()

你的路由器看起来像这样:-

Your router would look something like this:-

ReactDOM.render((
     <Router history={browserHistory}>
      <Route path="/content" component={app}>
        <IndexRoute component={home}/>
        <Route path="/content/:slug" component={component_name} />
      </Route>
    </Router>
), document.getElementById('app'));

所以现在当您调用 www.example.com/content/a 时,a 将被视为 slug.在该组件中,如果您调用 www.example.com/content/b , b 将被视为 slug 并且可用作 componentWillReceiveProps 中的 nextProps 参数.

So now when you call www.example.com/content/a, a would be taken as slug. Within that component if you call www.example.com/content/b , b would be taken as slug and would be available as nextProps parameter in componentWillReceiveProps.

希望能帮到你!!

这篇关于在 url 更改时,我想重新呈现我的组件我应该怎么做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆