【问题标题】:Uncaught TypeError: match is undefined未捕获的类型错误:匹配未定义
【发布时间】:2022-01-06 15:50:07
【问题描述】:
import books from '../books'


function BookScreen({ match }) {
    const book = books.find((b) => b._id === match.params.id)
    return (
        <div>
            {book}
        </div>
    )
}

export default BookScreen

我不断收到错误匹配未定义。我看到了一个包含类似代码的教程,但是在测试时似乎还不错。任何线索可能是什么问题?

【问题讨论】:

  • 您应该尝试使用useParams() 获取网址参数的新方法

标签: javascript reactjs react-router frontend


【解决方案1】:

如果 match 属性未定义,这可能是由于一些原因。

react-router-domv5

如果在 match 属性未定义的情况下使用 RRDv5,这意味着 BookScreen 没有接收到在 Route 组件的 component 属性或 @ 上呈现组件时注入的 route props 987654333@ 或 children 道具功能。请注意,使用children 路由将匹配并呈现,请参阅route render methods 了解详细信息。

确保执行以下操作之一来访问match 对象:

  1. Routecomponent 属性上渲染BookScreen

    <Route path="...." component={BookScreen} />
    
  2. Routerenderchildren 属性函数上渲染BookScreen 并传递路由属性

    <Route path="...." render={props => <BookScreen {...props} />} />
    

    <Route path="...." children={props => <BookScreen {...props} />} />
    
  3. withRouter 高阶组件装饰BookScreen 以注入路由道具

    import { withRouter } from 'react-router-dom';
    
    function BookScreen = ({ match }) {
      const book = books.find((b) => b._id === match.params.id)
      return (
        <div>
          {book}
        </div>
      );
    };
    
    export default withRouter(BookScreen);
    
  4. 由于BookScreen是一个React函数组件,导入并使用useParams钩子访问路由匹配参数

    import { useParams } from 'react-router-dom';
    
    ...
    
    function BookScreen() {
      const { id } = useParams();
      const book = books.find((b) => b._id === id)
      return (
        <div>
          {book}
        </div>
      );
    }
    

react-router-domv6

如果使用 RRDv6,则没有 match 属性。路线道具不见了。这里只存在useParams等钩子,所以使用它们。

import { useParams } from 'react-router-dom';

...

function BookScreen() {
  const { id } = useParams();
  const book = books.find((b) => b._id === id)
  return (
    <div>
      {book}
    </div>
  );
}

如果您有其他类组件并且您正在使用 RRDv6,并且您不想将它们转换为函数组件,那么您需要创建一个自定义 withRouter 组件。详情见我的回答here

【讨论】:

  • 很好的答案。感谢您包含 V6
【解决方案2】:

我猜你在匹配初始化之前渲染了 BookScreen 组件。这就是为什么在 BookScreen 渲染时 match 未定义的原因。像下面这样有条​​件地渲染它。

return (
  ... other components
 {match && <BookScreen match={match}/>}

)

另外,我留下了有用的网站,它告诉你一些好的方法来做到这一点。 :D

https://www.digitalocean.com/community/tutorials/7-ways-to-implement-conditional-rendering-in-react-applications

希望你能找到答案:D

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 2021-05-13
    • 2021-08-11
    • 2020-12-21
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2021-11-16
    • 2021-08-16
    相关资源
    最近更新 更多