簡體   English   中英

路由參數更改時刷新組件

[英]Refresh Component on route parameter change

為什么更改路由參數時組件不更新道具?

嘗試在componentWillReceiveProps中使用setState但它甚至沒有觸發?

export default class HomePage extends React.PureComponent {
  movies = require('../../movieList.json');
  state = {
    match: this.props.match,
    id: null
  }

  componentWillReceiveProps(np) {
    if(np.match.params.id !== this.props.match.params.id) {
      console.log('UPDATING PROPS')
      this.setState({ match: np.match })
    }
  }

  render() {
    const { match } = this.props;

    const movie = this.movies[match.params.id || movieOrder[0]];
    const nextMovie = getNextMovie(match.params.id || movieOrder[0]);
    const prevMovie = getPrevMovie(match.params.id || movieOrder[0]);
    return (
      <>
        <h1>{movie.title}</h1>
        <Link to={nextMovie}>Next</Link>
        <Link to={prevMovie}>Prev</Link>
      </>
    );
  }
}

nextMovieprevMovie獲取應該在鏈接中設置的 id。 不幸的是,它僅在第一次渲染期間設置。 單擊時,我可以看到 url 更改,但沒有觸發更新

這是持有開關的組件

export default class App extends React.PureComponent {

  state = {
    isLoading: true,
  }

  componentDidMount() {
    PreloaderService.preload('core').then(() => {
      console.log('LOADED ALL');
      console.log('PRELOADER SERVICE', PreloaderService);
      this.setState({ isLoading: false });
      console.log('Preloader assets', PreloaderService.getAsset('dog-video'))
    });
  }

  render() {
    const { isLoading } = this.state;

    if(isLoading) {
      return(
        <div>
          is loading
        </div>
      )
    }
    return (
      <div>
        {/* <Background /> */}
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/:id" component={props => <HomePage {...props} />} />
          <Route component={NotFoundPage} />
        </Switch>
        <GlobalStyle />
      </div>
    );
  }

}```

這里有幾件事。 componentWillReceiveProps被認為是不安全的,已棄用 嘗試改用componentDidUpdate 此外,您的 class 組件需要一個constructor 因為它現在是state被定義為 static 變量。

constructor(props) {
  super(props);
  this.state = {
    match: this.props.match,
    id: null
  }
}

componentDidUpdate(np) {
  if(np.match.params.id !== this.props.match.params.id) {
    console.log('UPDATING PROPS')
    this.setState({ match: np.match })
  }
}

最后,仔細檢查以確保您的邏輯是正確的。 現在NextPrev按鈕鏈接到同一個東西:

const nextMovie = getNextMovie(match.params.id || movieOrder[0]);
const prevMovie = getPrevMovie(match.params.id || movieOrder[0]);

<Link to={nextMovie}>Next</Link>
<Link to={prevMovie}>Prev</Link>

作為替代方案,如果您想堅持使用componentWillReceiveProps ,您需要取消綁定當前電影,然后用新電影重新綁定它。 這是一個與用戶做完全相同的事情的代碼示例

似乎正在使用我的代碼沙盒娛樂

我不得不對缺少的代碼進行一些即興創作:

movieOrder[0]的值是多少? 0match.params.id的有效值嗎?

getNextMovieprevMovie長什么樣子?

此外,您沒有在render邏輯中使用Home組件的 state,所以我認為,即使沒有它們,它也應該渲染正確的電影。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM