未捕获的TypeError:未定义匹配 [英] Uncaught TypeError: match is undefined

查看:32
本文介绍了未捕获的TypeError:未定义匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import books from '../books'


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

export default BookScreen

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

推荐答案

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

react-router-domv5

如果在match道具未定义的情况下使用RRDv5,这意味着BookScreen没有接收在Route组件的component道具或renderchildren道具函数上呈现组件时注入的route props。请注意,使用children无论如何,路由都将匹配并呈现,有关详细信息,请参阅route render methods

确保实现以下操作之一来访问match对象:

  1. Routecomponent道具上渲染BookScreen

    <Route path="...." component={BookScreen} />
    
  2. renderchildren的道具函数上渲染BookScreen并通过Route传递路线道具

    <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是Reaction函数组件,请导入并使用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

这篇关于未捕获的TypeError:未定义匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆