TypeError: Cannot read property 'url' of undefined
使用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><h2>This is Home</h2></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><h4>{match.params.name}</h4></div>)} /> </div> )}const Products=()=>(<div><h3>This is Products</h3></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初学者可以借鉴一下。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。