更改路线参数时刷新组件

时间:2019-10-08 19:45:08

标签: javascript reactjs

为什么更改路线参数时组件不更新道具?

试图在setState内使用componentWillReceiveProps,但它甚至不会触发?

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>
    );
  }

}```

2 个答案:

答案 0 :(得分:0)

这里有几件事。 componentWillReceiveProps被认为是不安全的,并且是deprecated。尝试使用componentDidUpdate instead。同样,您的类组件也需要一个constructor。到目前为止,state被定义为静态变量。

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,则需要取消绑定当前电影,然后将其与新电影重新绑定。这是code example与用户做的完全相同的事情。

答案 1 :(得分:0)

似乎正在与我的codesandbox recreation合作。

我不得不对缺少的代码进行即兴创作:

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

getNextMovieprevMovie的样子如何?

此外,您没有在Home逻辑中使用render组件的状态,所以我认为,即使没有它们,它也应该呈现正确的电影。