开发者问题收集

无法解构“undefined”的属性“history”,因为它未定义。——React.js

2021-01-20
2541

我在路由器的 AddMovie 组件中使用了“history”对象。但在三行之后,我再次使用它,它给出了这个错误: TypeError:无法解构“undefined”的属性“history”,因为它未定义。

77 |    <Route path="/add" render = { ({history}) => (
 78 |   <AddMovie onAddMovieprop={(newMovie) => { this.addMovie(newMovie); history.push("/"); }} />
  79 | )}>
  80 | </Route>
> 81 | <Route path="/edit/:id" render = { ( props, {history} ) => (
     | ^  82 |   <EditMovie {...props} onEditMovieProp = {(id, updatedMovie) => { this.editMovie(id, updatedMovie); this.props.history.push("/"); }}/>
  83 |     )}>
  84 | </Route>

这是我的 App.js 代码渲染的一部分:

render(){
    let filteredMovies = this.state.movies.filter(
      movie => { return (movie.name.indexOf(this.state.searchQuery.toLowerCase()) !== -1) }
    ).sort((a,b) => {
      return a.name > b.name ? 1 : b.name> a.name ? -1 : 0; 
    })
    return (
     <Router>
        <div className="App">
          <Switch>
            <Route path="/" exact render = {() => (
              <div className="container" >
                <Searcher searchMovieProp = {this.searchMovie} addHistoryProp = {this.addHistory} />
                <MovieList movies= {filteredMovies} removeMovieProp = {this.removeMovie} />
              </div>
            )}>
            </Route>
            <Route path="/add" render = { ({history}) => (
              <AddMovie onAddMovieprop={(newMovie) => { this.addMovie(newMovie); history.push("/"); }} />
            )}>
            </Route>
            <Route path="/edit/:id" render = { ( props, {history} ) => (
              <EditMovie {...props} onEditMovieProp = {(id, updatedMovie) => { this.editMovie(id, updatedMovie); history.push("/"); }}/>
                )}>
            </Route>
          </Switch>
        </div>
     </Router>
    );
  }
2个回答

这是您需要做的:

<Route
  path="/edit/:id"
  render={({history, ...props}) => (
    <EditMovie
      {...props}
      onEditMovieProp={(id, updatedMovie) => {
        this.editMovie(id, updatedMovie);
        history.push("/");
      }}
    />
  )}
></Route>;
Taghi Khavari
2021-01-20

它会给出错误,因为该行上的 this.props 未定义 将

this.props.history.push("/");

更改为

history.push("/")
Sinan Yaman
2021-01-20