var React = require('react'),
ReactDOM = require('react-dom'),
History = require('react-router');
var APP = React.createClass({
mixins: [ History ],
render: function() {
return (
<div>
<div onClick={() => this.history.pushState(null, '/foo')}>Go to foo</div>
<div onClick={() => this.history.replaceState(null, 'bar')}>Go to bar without creating a new history entry</div>
<div onClick={() => this.history.goBack()}>Go back</div>
</div>
)
}
});
ReactDOM.render(<APP></APP>, document.getElementById('app'));
报错 Cannot read property 'pushState' of undefined
而且replaceState
等都是报了undefined
// 2.X使用
import { browserHistory } from 'react-router'
const DeepComponent = React.createClass({
handleSubmit() {
browserHistory.push(...)
}
}
History = require('react-router/lib/history') ??
或者 import {History} from 'react-router' ??
import { History } from 'react-router';
其实如果你调用History的Component是直接被react-router管理的话,你不需要mixin History。
直接在this.props就有,这是自动加进来的。
this.props.history.pushState(null, '/foo')}
楼上的答案是对的,我验证过了。