简体   繁体   English

如何在 url 更改时重新渲染 react 组件?

[英]How do I re-render react components on url change?

I have a route like so:我有一条这样的路线:

<BrowserRouter>
      <Switch>
        <Route path="/question/:title" component={Item} />
      </Switch>
    </BrowserRouter>

The component uses axios to fetch data and update the content on the site, this is done in the componentWillMount function:该组件使用axios来获取数据并更新站点上的内容,这是在componentWillMount函数中完成的:

componentWillMount(){
        const {title} = this.props.match.params;
        axios.get(server + '/api/question/slug/' + title)
                .then(response => {
                    this.setState({
                        question: response.data,
                        loading: false
                    })

                })
    }

The problem now is that, let's say I'm on a page "site.com/question/this-is-an-article", and I use <Link to="/question/second-article">Second Article</Link> to navigate, it's like the componentWillMount function is not being called so the former content still remains on the page.现在的问题是,假设我在“site.com/question/this-is-an-article”页面上,我使用<Link to="/question/second-article">Second Article</Link>导航,就像没有调用componentWillMount函数一样,所以以前的内容仍然保留在页面上。 How can I make the componentWillMount function to run when there is a change in the url?当 url 发生变化时,如何使componentWillMount函数运行?

First of all, use safe life-cycle is preferred react-lifecycle-methods-diagram首先,首选使用安全生命周期react-lifecycle-methods-diagram

Since you are using react-router-dom , you can get your URL via render props like this, refer to document here由于您使用的是react-router-dom ,您可以通过这样的渲染道具获取您的网址,请参阅此处的文档

history.location.pathname

So you may try to check if url changed in shouldComponentUpdate like this因此,您可以尝试像这样检查shouldComponentUpdate url 是否更改

shouldComponentUpdate(prevProps, prevState) {
  return this.props.history.location.pathname !== prevProps.history.location.pathname
}

You can add more condition inside of it, or just prevent complex condition via component design adjustment您可以在其中添加更多条件,或者只是通过组件设计调整来防止复杂条件

Try using the componentDidUpdate for the axios calling.尝试使用componentDidUpdate进行 axios 调用。 Necessarily - you want to call the api when title(a prop) parameter change.必然 - 您想在 title(a prop) 参数更改时调用 api。

You may also try componentWillReceiveProps / UNSAFE_componentWillReceiveProps for the same.您也可以尝试使用componentWillReceiveProps / UNSAFE_componentWillReceiveProps

PS - use componentDidMount along with above aptly. PS - 适当地使用componentDidMount以及上面的内容。 Look for lifecycle here http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/在这里寻找生命周期http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

I think you don't need any life cycle, (if yes, just use componentDidMount):我认为您不需要任何生命周期,(如果是,只需使用 componentDidMount):

class App extends Component {
  constructor() {
    super();
    this._initHistoryListen();
  }
  _unListen = () => {};
  _initHistoryListen() {
    this._unListen = history.listen((location, action) => {
      const {
        title
      } = this.props.match.params;
      axios.get(server + '/api/question/slug/' + title)
        .then(response => {
          this.setState({
            question: response.data,
            loading: false
          })

        })
    });
  }
  componentWillUnmount(){
     this._unListen()
  }
}

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

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