React Router 4 Failed上下文类型失败

时间:2017-10-02 15:19:49

标签: javascript reactjs react-router react-router-v4

我已将反应路由器4插入我的react-create-app并运行npm run test时出现以下错误:

 Warning: Failed context type: The context `router` is marked as required in `Switch`, but its value is `undefined`.
        in Switch (at App.js:17)
        in main (at App.js:16)
        in div (at App.js:15)
        in App (at App.test.js:7)

我正在使用react-router@4.2.0和react-router-dom@4.2.2

我确保我的<Switch>组件嵌套在<BrowserRouter>

App.js:

import React, { Component } from 'react';
import { Switch, Route, withRouter, Router } from 'react-router-dom';
import './App.css';

// Components
import Header from '../../components/header/Header';
import Nav from '../../components/nav/Nav';
import Dashboard from './../../containers/dashboard/Dashboard';
import Events from './../../containers/events/Events';
import NotFound from './../../containers/notfound/NotFound';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Header />
        <Nav />
            <main id="main">
                <Switch context="router">
                  <Route path="/" exact component={Dashboard} />
                  <Route path="/events" exact component={Events} />
                  <Route path="*" component={NotFound} />
              </Switch>
            </main>
          </div>
    );
  }
}

export default App;

和我的index.js

import ReactDOM from 'react-dom';
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import Store from './store';
import App from './containers/app/App';

import './index.css';

const StoreInstance = Store();

ReactDOM.render(
 <Provider store={StoreInstance}>
    <BrowserRouter>
    <App />
  </BrowserRouter>
 </Provider>,
 document.getElementById('root')
);

还有其他人遇到过这个吗?

1 个答案:

答案 0 :(得分:3)

这是Create React App的默认测试示例。

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

路由器上下文在'index.js'文件中提供,在运行测试时不存在。

你应该在下一步重写它​​:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './App';


it('renders without crashing', () => {
  const div = document.createElement('div');

  const StoreInstance = Store();

  ReactDOM.render(
     <Provider store={StoreInstance}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
     </Provider>, 
     div
  );
});

或将'Provider'和'BrowserRouter移动到'App'组件。