在 componentDidMount 中导航-react-router-dom v6

yas*_*ili 5 reactjs react-router-dom

这是我第一次使用react-router-dom v6,我对v4很熟悉。

我有一个电影列表,每部电影都有一个 id,如果用户在 url 中输入了错误的电影 id,我需要导航到未找到的页面。

我使用类组件的问题所以我坚持使用 componentDidMount 这会导致以下错误

You should call navigate() in a React.useEffect(), not when your component is first rendered.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

 componentDidMount() {
    let { id } = this.props.params;
    const genres = getGenres();
    this.setState({ genres });
    const movieId = id;
    if (movieId === 'new') return;
    const movie = getMovie(movieId);
    if (!movie) return this.props.navigate('/not-found', { replace: true });
    this.setState({ data: this.mapToViewModel(movie) });
  }
Run Code Online (Sandbox Code Playgroud)

正如我提到的,我正在使用类组件,因此我将类导出为函数以使 Useparams() 与我一起使用

function WithNavigate(props) {
  let navigate = useNavigate();
  return <MovieForm {...props} params={useParams()} navigate={navigate} />;
}

export default WithNavigate;
Run Code Online (Sandbox Code Playgroud)

我现在的问题是如何使导航在 componentDidMount 中工作!

先感谢您

Ant*_*ang 6

componentDidMount之后渲染useEffect()

对于简单的修复,您可以添加

let { navigate } = this.props;
Run Code Online (Sandbox Code Playgroud)

像这样的代码,用setTimeOut

 componentDidMount() {
    let { id } = this.props.params;
    let { navigate } = this.props;

    const genres = getGenres();
    this.setState({ genres });
    const movieId = id;

    if (movieId === 'new') return;
    const movie = getMovie(movieId);
    if (!movie) {
           return setTimeOut(()=> this.props.navigate('/not-found', { replace: true }));
    }
    this.setState({ data: this.mapToViewModel(movie) });
  }
Run Code Online (Sandbox Code Playgroud)