无法读取undefined属性'push'

时间:2016-04-05 03:48:30

标签: javascript reactjs react-router

我试图用反应路由器做很简单的事情。但我继续遇到错误 - '无法读取属性'推送'未定义'。当我点击测试链接时会发生这种情况。

import { Router, useRouterHistory, Route } from 'react-router';
import { createHashHistory } from 'history';
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

ReactDOM.render(React.createElement(nav), document.getElementById('navComponent'));

ReactDOM.render((
    <Router history={appHistory}>
        <Route path="test" component={Test}/>
    </Router>
), document.getElementById('mainContainer'));

nav组件

render() {
        return (
            <div>
              <ul>
               <li><Link to="/test"> Test </Link></li>
              </ul>    
            </div>
        );
    };

测试组件

render() {
        return (
            <div>
              Hello World!   
            </div>
        );
    };

有人可以帮帮我吗?被困在这里。

更新1

推送是react-router

的一部分
this.context.router.push(_location);

的package.json

{

  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^3.9.0",
    "gulp-sass": "^2.1.1",
    "gulp-util": "^3.0.7",
    "imports-loader": "0.6.4",
    "istanbul-instrumenter-loader": "0.1.3",
    "jasmine": "2.3.2",
    "jasmine-core": "2.3.4",
    "jquery": "1.11.3",
    "moment": "2.10.6",
    "react": "0.14.2",
    "react-addons-test-utils": "0.14.2",
    "react-dom": "0.14.2",
    "redux": "3.0.3",
    "rewire": "2.5.1",
    "rewire-webpack": "1.0.1",
    "run-sequence": "^1.1.5",
    "style-loader": "0.12.4",
    "underscore": "1.8.3",
    "webpack-stream": "^3.1.0"
  },
  "dependencies": {
    "react-router": "^2.0.0",
  }
}

更新2 很抱歉没有明确我的问题,我已经更新了我的问题,希望它现在更有意义

1 个答案:

答案 0 :(得分:0)

它的作用如下。请比较您的解决方案。基本上最顶层的路线应该具有“/”的路径,对于儿童“/”不是必需的

<Router history={appHistory}>
        <Route path="/" component={Main}>
            <Route path="test" component={Test}/>
            <Route path="*" component={Test}/>
        </Route>
</Router>

const Main = ({children, history}) => {
return (
<div>
<nav>
        <div history={history}/>
      </nav>
      <div>
        {children}
      </div>
</div>
 )
}