reactjs - 在 url 更改时,我想重新渲染我的组件,我应该怎么做

标签 reactjs react-router

我有两个获取示例组件的链接,但是当我单击其中任何一个时,它会被加载,而当我单击另一个链接时,它不会重新渲染,只会更改 url。我想在两次链接点击时重新渲染组件。有什么办法可以做到吗?

最佳答案

当我从事 React 项目时,我曾经遇到过类似的问题。

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

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

更新

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

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

为了让组件第一次加载时更清楚,通过调用 url www.example.com/content/a 来运行 componentDidMount()

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

现在您可以保留一个常用函数,例如 initializeComponent() 并从 componentDidMount()componentWillReceiveProps() 调用它

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

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 参数使用。

希望对你有帮助!!

关于reactjs - 在 url 更改时,我想重新渲染我的组件,我应该怎么做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38915066/

相关文章:

javascript - React 路由器向下滚动新页面

reactjs - React Router 中的 matchPath 似乎没有考虑 Basename

javascript - 在 protected 路线 reactjs 中传递 Prop

reactjs - 在react-router 2.4.0中重定向willTransitionTo?

javascript - React 中的状态未渲染到屏幕上

javascript - ReactJS 和类名

javascript - 语法错误 : Unexpected token, 预期 { (1 :7) , create-react-app

css - 嗨,类不适用于焦点上的输入元素

javascript - 如何合并具有空字符串值的对象?

javascript - react : How can I dynamically render images mapping through a list?