TypeError: Cannot read property 'url' of undefined

发布时间:2020-06-28 17:35:39 作者:googlingman
来源:网络 阅读:2849

引言

使用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时,出现下面语法错误提示:
TypeError: Cannot read property 'url' of undefined

纠错

正如前面所提及的,问题出在临近结尾处的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初学者可以借鉴一下。

推荐阅读:
  1. 如何使用JavaScript UI控件(WijmoJS)构建
  2. 组件的生命周期是什么?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react router fin

上一篇:Pytorch自定义层出现多Variable共享内存错误怎么办

下一篇:windows服务器远程执行命令(PowerShell+WinRM)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》