反应路由器类型错误:_this.props.history 未定义 [英] React-router TypeError: _this.props.history is undefined
问题描述
我正在使用 react-router 和 react js,我遵循他们的文档但面临此错误
编译时报错,
TypeError: _this.props.history 未定义
这是我的 index.js 文件
从'react'导入React;从 'react-dom' 导入 ReactDOM;从'./App'导入应用程序;导入'./index.css';import { Router, Route, browserHistory, IndexRoute } from 'react-router';ReactDOM.render(<路由器历史={browserHistory}><Route path="/" component={App}></路线></路由器>,document.getElementById('root'));
这是我的 App.js 文件
import React, { Component } from 'react';导入'./App.css';类 App 扩展组件 {构造函数(道具){超级(道具);this.state = {headerText: "来自标题的道具.",contentText: "来自内容的道具."};}使成为() {返回 (<div className="应用程序"><ul><li><a href="">首页</a></li><li><a href="">首页</a></li><li><a href="">首页</a></li>
);}}导出默认应用程序;
这是因为 React Router 从 4.0.0 开始发生了变化.当您使用 browserHistory
时,您现在应该使用 react-router-dom
包中的 BrowserRouter
.所以你的代码看起来像:
从'react'导入React;从 'react-dom' 导入 ReactDOM;从'./App'导入应用程序;导入'./index.css';从'react-router-dom'导入{ BrowserRouter, Route };ReactDOM.render(<浏览器路由器><Route path="/" component={ App }/></BrowserRouter>, document.getElementById('root'));
当然,您需要先安装 react-router-dom
.
另请注意,如果您使用多个 Route
元素,则必须使用 Switch
,如在这个答案中.
I am using react-router with react js and i following their documentation but facing this error
while compiling it shows the error,
TypeError: _this.props.history is undefined
this is my index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
</Route>
</Router>
,
document.getElementById('root')
);
and this is my App.js file
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
headerText: "Props from Header.",
contentText: "Props from content."
};
}
render() {
return (
<div className="App">
<ul>
<li><a href="">Home</a></li>
<li><a href="">Home</a></li>
<li><a href="">Home</a></li>
</ul>
</div>
);
}
}
export default App;
This is because things changed in React Router starting with 4.0.0. You should now use BrowserRouter
from react-router-dom
package when you were using browserHistory
. So your code will looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter, Route } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<Route path="/" component={ App }/>
</BrowserRouter>, document.getElementById('root')
);
Of course, you'll need to install react-router-dom
first.
Also note that if you're using more than one Route
element, you'll have to use a Switch
as explained in this answer.
这篇关于反应路由器类型错误:_this.props.history 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!