上下文“ router.history”在“链接”中标记为必需,但其值为“未定义”。

时间:2018-10-07 15:29:13

标签: reactjs tabs react-router

在我的react应用程序中构建一个Tabs期间,我遇到了错误

 warning.js:33 Warning: Failed context type: The context 
   `router.history` is marked as required in `Link`, but 
  its value is `undefined`.
in Link (created by ChatIndexContainer)
in li (created by ChatIndexContainer)
in ul (created by ChatIndexContainer)
in div (created by ChatIndexContainer)
in div (created by ChatIndexContainer)
in ChatIndexContainer (created by Connect(ChatIndexContainer))
in Connect(ChatIndexContainer) (created by RouterContext)
in RouterContext (created by Router)
in Router (created by App)
in App
in Provider

据我发现,此问题是react-router的版本。我正在使用"react-router": "~3.2.0""react-router-dom": "^4.2.2",但必须至少使用4.0.0。全部更新后,我的React应用崩溃了。还有其他解决方案可解决此错误并保持当前的react-router版本吗?

这里是产生此错误的组件:

import React, { Component } from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import { connect } from 'react-redux';
import * as chatActions from '../actions/chats';
import MessageTile from '../components/MessageTile';

 class ChatIndexContainer extends Component {
   constructor(props) {
     super(props);
   }

   render() {
    return(
      <div>
       <div className="links">
        <ul>
        <li>
          <Link to={`/chats`}></Link>
        </li>
      </ul>
    </div>
    <div className="tabs">
      <Switch>
        <Route path={`/chats/:chatId`} component={MessageTile} />
      </Switch>
    </div>
  </div>
  )
 }
}

export default connect(
  state => ({
   chats: state.chats
  }),
  chatActions
)(ChatIndexContainer);

1 个答案:

答案 0 :(得分:0)

您的链接和路由组件必须存在于自定义历史记录组件随附的BrowserRouter,HashRouter或Router中

class ChatIndexContainer extends Component {
   constructor(props) {
     super(props);
   }

   render() {
    return(
        <BrowserRouter>
           <div>
               <div className="links">
                <ul>
                <li>
                  <Link to={`/chats`}></Link>
                </li>
              </ul>
            </div>
            <div className="tabs">
              <Switch>
                <Route path={`/chats/:chatId`} component={MessageTile} />
              </Switch>
            </div>
          </div>
        </BrowserRouter>  
      )
   }
}

export default connect(
  state => ({
   chats: state.chats
  }),
  chatActions
)(ChatIndexContainer);