reactjs - 无法读取未定义的属性推送 [英] reactjs - can not read property push of undefined
本文介绍了reactjs - 无法读取未定义的属性推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码.我想要做的是当我单击功能"按钮时,它会将我带到索引路线.但是,React 一直说无法读取未定义的属性推送"我做错了什么?
route.js
从react"导入React;从react-dom"导入 ReactDOM;从反应路由器"导入 {Router, Route, hashHistory, IndexRoute };从./page/Layout"导入布局;从./page/Features"导入功能;从./page/archive"导入功能;const app = document.getElementById('app');ReactDOM.render(<路由器历史={hashHistory}><Route path="/" component={Layout}><IndexRoute 组件={Features}/><Route path="archive" component={Archive}/></路线></路由器>, 应用程序);
布局组件
从react"导入React;从react-router"导入 {Link, Router, Route, hashHistory};导出默认类布局扩展 React.Component{导航(){this.context.router.push('/');}使成为(){返回(<div>{this.props.children}<button onClick={this.navigate.bind(this)}>功能</button>
)}}
package.json - 部分
"react": "^0.14.7","react-dom": "^0.14.7",反应路由器":^ 2.0.1""历史": "^2.0.1",
-------------更新乔丹的回答-------------
解决方案
export default class Layout extends React.Component{导航 = () =>{this.context.router.push('/');}使成为(){返回(<div>{this.props.children}<button onClick={this.navigate.bind(this)}>功能</button>
)}}Layout.contextTypes = {路由器:PropTypes.object.isRequired}
I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?
route.js
import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory, IndexRoute } from "react-router";
import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";
const app = document.getElementById('app');
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Features} />
<Route path="archive" component={Archive} />
</Route>
</Router>, app);
Layout component
import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
navigate(){
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}
package.json - partial
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
"history": "^2.0.1",
-------------update to jordan's answer-------------
解决方案
export default class Layout extends React.Component{
navigate = () => {
this.context.router.push('/');
}
render(){
return(
<div>
{this.props.children}
<button onClick={this.navigate.bind(this)}>feature</button>
</div>
)
}
}
Layout.contextTypes = {
router: PropTypes.object.isRequired
}
这篇关于reactjs - 无法读取未定义的属性推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文