【问题标题】:React Router DOM can't read location stateReact Router DOM 无法读取位置状态
【发布时间】:2020-07-09 13:17:09
【问题描述】:

我以前见过这个问题,但只适用于 Class 组件,所以我不确定如何将相同的方法应用于功能组件。

很简单,我有一个链接<Link to={{ pathname="/first-page" state: { name: "First person" }>First Page</Link>然后在组件FirstPage.js我需要读取name的状态所以我尝试了以下:

import React from "react";

export default props => {
  React.useEffect(() => {
    console.log(props)
  }, []);
  return (
    <div>
      <h1>First Page</h1>
      <p>Welcome to first page, {props.location.state.name}</p>
    </div>
  );
};

我一直在阅读React Router location documentation,它应该将状态作为组件属性传递,但事实并非如此。我很确定我做错了什么或根本没有看到。

如果你想尝试一下整个代码,我会在这里留下一个CodeSandbox project 来“测试”这个。

因此,对我做错了什么有任何想法吗?提前致谢。

【问题讨论】:

    标签: javascript node.js reactjs react-router state


    【解决方案1】:

    这不是基于类与功能组件的问题,而是路由如何工作的问题。 Wrapped children 不接收路由参数,但使用Routecomponentrenderchildren 属性渲染的任何东西都可以。

    Route render methods

    <Switch>
      <Route path="/first-page" component={FirstPage} />
      <Route path="/second-page" component={SecondPage} />
    </Switch>
    

    另一种选择是使用withRouter HOC 导出装饰页面组件,或者如果是功能组件,则使用挂钩。

    withRouter

    您可以访问history 对象的属性和最近的 &lt;Route&gt;match 通过 withRouter 高阶组件。 withRouter 将更新的 matchlocationhistory 道具传递给被包装的 组件无论何时呈现。

    const FirstPage = props => {
      React.useEffect(() => {
        console.log(props)
      }, []);
    
      return (
        <div>
          <h1>First Page</h1>
          <p>Welcome to first page, {props.location.state.name}</p>
        </div>
      );
    };
    
    export default withRouter(FirstPage);
    

    hooks

    React Router 附带了一些hooks,可让您访问 路由器并从组件内部执行导航。

    const FirstPage = props => {
      const location = useLocation();
    
      console.log(location);
    
      return (
        <div>
          <h1>First Page</h1>
          <p>Welcome to first page, {location.state.name}</p>
        </div>
      );
    };
    
    export default FirstPage;
    

    【讨论】:

    • 无论如何,我将使用第二个答案中的useLocation() 方法来使用钩子。
    • 啊,是的,它们也有钩子,但我发现使用 react-router-dom 钩子测试组件比使用 withRouter HOC 的组件更乏味,因为它是 更容易 传递模拟道具。我会更新答案。
    【解决方案2】:

    我发现您的路由器有问题。而不是使用:

     <Route path="/first-page">
        <FirstPage/>
     </Route>
    

    用途:

    <Route path="/first-page" component={FirstPage}/>
    

    否则使用库let location = useLocation();提供的钩子,这样你就可以访问位置对象了。

    【讨论】:

    • 嗯,这也很好。最后一种方法让我使用钩子,所以我不需要修改所有代码。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2021-09-07
    • 2020-12-22
    • 1970-01-01
    • 2018-10-24
    • 2023-03-17
    • 2020-05-08
    • 2022-11-18
    相关资源
    最近更新 更多