React-Router不断给我一个警告:你不能改变<router routes =“”>

时间:2016-05-10 20:29:17

标签: javascript reactjs react-router

我在我的应用程序中使用React-Router并使用个性化历史记录对象。

看起来像这样:

import { createHistory } from 'history';
import { Router, Route, IndexRedirect, useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

...

componentWillMount() {
    const browserHistory = useRouterHistory(createHistory)({
        basename: '/sign',
    });

    this.history = syncHistoryWithStore(browserHistory, store, {
        selectLocationState: (state) => state.routing,
    });
}

render() {
    const history = this.history;

    return (
        <Router history={history}>
            <Route path="/" component={Sign}>
                <IndexRedirect to="/login" />
                <Route path="login" component={Login} />
            </Route>
        </Router>
    );
}

因此,当我访问mywebsite.com/sign时,它会将我重定向到mywebsite.com/sign/login,这很好,但我在控制台中收到此错误:

Warning: [react-router] You cannot change <Router routes>; it will be ignored

如果我直接访问登录页面,我不会收到任何错误。

知道什么是错的吗?

由于

1 个答案:

答案 0 :(得分:0)

可能正在发生,因为您的“路由器组件”正在尝试每次更改某些内容时重新呈现(可能是历史记录)。

为路线使用const更容易

const browserHistory = useRouterHistory(createHistory)({
    basename: '/sign',
});

const history = syncHistoryWithStore(browserHistory, store, {
    selectLocationState: (state) => state.routing,
});

const routes = (<Route path="/" component={Sign}>
                <IndexRedirect to="/login" />
                <Route path="login" component={Login} />
            </Route>)

ReactDOM.render(
  <Router history={history}>
    {routes}
  </Router>,
  yourElement
);