分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

TypeError: Cannot read property ‘url‘ of undefined

发布时间:2023-09-06 01:56责任编辑:蔡小小关键词:url
引言

使用React-router感觉还是有一定「曲线」的,首先要熟悉ES6且不说,对于JSX扩展语法及React-router有关路由表达稍有马虎都不可以。当出现如题所示错误时,我在网络上搜索,竟然没有找到几处可参考的。倒是有一个如下:

https://teamtreehouse.com/community/typeerror-cannot-read-property-url-of-undefined

的情况与我这里也不一样,后来在stackoverflow.com上直接搜索,也没有找到。不是受到前者的启发,还是终于把问题挖出来,欣喜之余,还是决定把它记录下来。

错误描述

import React, { Component } from ‘react‘;import { ???Link, ???Route,} from ‘react-router-dom‘;const Home=()=>(<div><h1>This is Home</h1></div>)const Category=({match})=>{ ???return( ???????<div> ???????????<ul> ???????????????<li><Link to={`${match.url}/shoes`}>Shoes</Link></li> ???????????????<li><Link to={`${match.url}/boots`}>Boots</Link></li> ???????????????<li><Link to={`${match.url}/footwear`}>Footwear</Link></li> ???????????</ul> ???????????<Route ???????????????path={`${match.path}/:name`} ???????????????render={({match})=>(<div><h3>{match.params.name}</h3></div>)} ???????????/> ???????</div> ???)}const Products=()=>(<div><h2>This is Products</h2></div>)class App extends Component{ ?render(){ ???return( ???????<div> ???????????<ul> ?????????????<li><Link to="/">Home</Link></li> ?????????????<li><Link to="/category">Category</Link></li> ?????????????<li><Link to="products">Products</Link></li> ???????????</ul> ?????????<hr/> ???????????<Route exact={true} path="/" component={Home}/> ???????????<Category/> ???????????<Route path="/products" component={Products}/> ???????</div> ???) ?}}export default App;

本例是想测试React-Router客户端嵌套路由相关结论的。上面代码中定义了组件Category,问题出现在临近结尾处的此组件的引用方式。通过WebStorm内置控制台运行npm start时,出现下面语法错误提示:

纠错

正如前面所提及的,问题出在临近结尾处的Category组件的引用方式,正确的表达应该是:

 ???????????????<Route exact={true} path="/" component={Home}/> ???????????????<Route path="/category" component={Category}/> ???????????????<Route path="/products" component={Products}/>

小结

在React-Router的世界里一切皆是组件,可能是受到前段时间使用Semantic-UI for React中表达的影响,以至于犯下上面浮浅错误。其中,在React-Router中<Route>组件嵌套多少层是不要紧的,只要有需要,而且几乎不拘位置。React-Router初学者可以借鉴一下。

TypeError: Cannot read property ‘url‘ of undefined

原文地址:http://blog.51cto.com/zhuxianzhong/2120579

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved