反应路由器v4错误链接组件

时间:2017-07-11 09:25:36

标签: javascript reactjs react-router

我有从react-router-dom

导入链接的组件
import React, { Component } from 'react';
import { Link } from 'react-router-dom';


class Sidebar extends Component{

  render() {
    return (
      <div className="be-left-sidebar">
        <div className="left-sidebar-wrapper"><a href="#" className="left-sidebar-toggle">Blank Page</a>
          <div className="left-sidebar-spacer">
            <div className="left-sidebar-scroll">
              <div className="left-sidebar-content">
                <ul className="sidebar-elements">
                  <li className="divider">Menu</li>
                  <li className="parent"><a href="#"><i className="icon mdi mdi-home" /><span>Home</span></a>
                    <ul className="sub-menu">
                      <li><Link to='/'>Home</Link>
                      </li>

                    </ul>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div className="progress-widget">
            <div className="progress-data"><span className="progress-value">60%</span><span className="name">Current Project</span></div>
            <div className="progress">
              <div style={{width: '60%'}} className="progress-bar progress-bar-primary" />
            </div>
          </div>
        </div>
      </div>
    );
  }

};

export default Sidebar;

然后console.log显示错误

  • Warning: Failed context type: The context router is marked as required in Link, but its value is undefined.
  • Cannot read property 'history' of undefined

`

我是新的反应,我正在使用反应路由器v4.1.1

谁能帮帮我? 谢谢

2 个答案:

答案 0 :(得分:1)

确保您的组件出现在<Router>组件中。

答案 1 :(得分:0)

在React路由器v4中,我们有来自react-router-dom的Switch,Route和Link组件,并按如下方式配置我们的路由器:

import { Switch, Route, Link } from 'react-router-dom';

  <span>LINKS:</span>
  <ul>
    <li onClick={this.props.goToDefault}><Link to={'/'}>Go To Default</Link></li>
    <li onClick={this.props.goToSub1}><Link to={'/left-sub1'}>Go To One</Link></li>
    <li onClick={this.props.goToSub2}><Link to={'/left-sub2'}>Go To Two</Link></li>
  </ul>
  <Switch>
    <Route exact path='/' component={LeftSubDefault} />
    <Route path='/left-sub1' component={LeftSubOne} />
    <Route path='/left-sub2' component={LeftSubTwo} />
  </Switch>

在app.js或您的条目文件中。将您的App组件包装在BrowserRouter中,如下所示:

import { BrowserRouter } from 'react-router-dom';

<BrowserRouter>
    <App />
</BrowserRouter>

Here是一篇很有帮助的文章。