我很难弄清楚如何在我的反应路由器中正确实现onChange。我希望我做的是改变我想重定向到家。遵循以下代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Home from './Home';
import Post_Form from './Post_Form';
import * as Firebase from 'firebase';
import Config from './utils/config.js';
import Auth from './utils/auth.js';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router';
class Root extends Component {
constructor(props) {
super(props);
this.state = {
};
}
routeChange(nextPathname, nextState, replace, cb) {
replace({
pathname: '/home',
state: {nextPathname: nextState.location.pathname}
});
cb();
}
render() {
return (
<Router history = {browserHistory}>
<Route path = "/" component = {App} onChange={this.routeChange.bind(this)}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path ="post-form" component={Post_Form} />
<Route path="*" component={Home}/>
</Route>
</Router>
)
}
}
ReactDOM.render(<Root />, document.getElementById('root'));
点击我获得的导航
Uncaught RangeError: Maximum call stack size exceeded
答案 0 :(得分:1)
我认为对replace的调用是触发另一个更改事件和另一个对routeChange的调用。这就是你的堆栈大小超出的原因。
您可以在调用replace之前尝试检查您是否已经在家。像这样:
if(nextState.location.pathname != '/home'){
replace({
pathname: '/home',
state: {nextPathname: nextState.location.pathname}
});
}
我在我的项目中做了类似的事情,虽然有onEnter,但我认为它也适用于onChange。