【问题标题】:Why is state undefined when passed through React Router Link Component?为什么通过 React Router Link 组件时状态未定义?
【发布时间】:2019-11-12 22:43:17
【问题描述】:

我正在尝试通过 React Router Link 组件传递道具,但状态仍未定义,有人知道为什么吗?

路线:

<Route path="/movie" component={Movie} render={props => 
<Movie {...props} />} />

链接:

<Link to={{ pathname: '/movie', state: { fromMovieList: true}}} > 
Title </Link>

从路径“/movie”渲染的组件

class Movie extends React.Component {

  render () {
    console.log(this.props.location.state); // undefined
    return (
      <div> Hello </div>
        )
      }
    }

export default Movie;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你必须用withRouter包裹Movie组件;

    您可以通过 withRouter 高阶组件访问历史对象的属性和最近的路由匹配。 withRouter 将在渲染时将更新的匹配、位置和历史道具传递给包装的组件。

    export default withRouter(Movie);
    

    【讨论】:

    • 通过使用子/链接组件中的 react-router useLocation 钩子使​​其在功能组件中工作。 reacttraining.com/blog/react-router-v5-1/#uselocation
    • 是的,不使用 withRouter 挂钩,但只需要 useLocation 挂钩即可。我遇到了同样的问题。
    猜你喜欢
    • 2019-08-08
    • 2019-08-11
    • 2021-11-05
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多