簡體   English   中英

如何在 url 更改時重新渲染 react 組件?

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

我有一條這樣的路線:

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

該組件使用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
                    })

                })
    }

現在的問題是,假設我在“site.com/question/this-is-an-article”頁面上,我使用<Link to="/question/second-article">Second Article</Link>導航,就像沒有調用componentWillMount函數一樣,所以以前的內容仍然保留在頁面上。 當 url 發生變化時,如何使componentWillMount函數運行?

首先,首選使用安全生命周期react-lifecycle-methods-diagram

由於您使用的是react-router-dom ,您可以通過這樣的渲染道具獲取您的網址,請參閱此處的文檔

history.location.pathname

因此,您可以嘗試像這樣檢查shouldComponentUpdate url 是否更改

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

您可以在其中添加更多條件,或者只是通過組件設計調整來防止復雜條件

嘗試使用componentDidUpdate進行 axios 調用。 必然 - 您想在 title(a prop) 參數更改時調用 api。

您也可以嘗試使用componentWillReceiveProps / UNSAFE_componentWillReceiveProps

PS - 適當地使用componentDidMount以及上面的內容。 在這里尋找生命周期http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

我認為您不需要任何生命周期,(如果是,只需使用 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