未捕获的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道具或render或children道具函数上呈现组件时注入的route props。请注意,使用children无论如何,路由都将匹配并呈现,有关详细信息,请参阅route render methods。
确保实现以下操作之一来访问match对象:
在
Route的component道具上渲染BookScreen<Route path="...." component={BookScreen} />在
render或children的道具函数上渲染BookScreen并通过Route传递路线道具<Route path="...." render={props => <BookScreen {...props} />} />或
<Route path="...." children={props => <BookScreen {...props} />} />使用
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);由于
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。
相关文章