javascript - 在构造函数中定义路由

标签 javascript reactjs ecmascript-6 react-router

我有一个名为 Root 的组件它呈现了我的 index.js 的路线

const store = configureStore();
ReactDOM.render(
  <Root store={store} />,
  document.getElementById('root'),
);

我需要这样做,因为我正在连接 Rootredux ,这是由于 root 授权 onEnter ,并且它需要与 redux 一起使用状态。

所以这是根:

class Root extends React.Component {
  constructor(props) {
    super(props);
    // some stuff
  }

  requireAuthentication = (nextState, replace) => {
    // some stuff for managing auth
  };

  render() {
    const { store } = this.props;
    return (
      <div>
        <Provider store={store}>
          <Router history={browserHistory}>
            <Route path="/" component={App}>
              <Route component={Dashboard}>
                <IndexRoute component={Home} onEnter={requireAuthentication}/>
              </Route>
              <Route path="login" component={Login} />
            </Route>
          </Router>
        </Provider>
      </div>
    );
  }
}

// some definitions for connecting Root to redux

export default connect(mapStateToProps, mapDispatchToProps)(Root);

好吧...这渲染得很好,但我有一个警告:

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

路线,也工作正常......但我想解决警告。所以...谷歌搜索我发现这个问题是一个可能的解决方案:声明 routes在构造函数内并将其传递给 Router通过props .

我的构造函数我这样做了:

import React, { PropTypes } from 'react';
import { connect, Provider } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Router, browserHistory, Route, IndexRoute } from 'react-router';
import { loginActions } from '../actions';
import { App, Dashboard, Home, Login } from '../features';
import adalHandler from '../services/adal';

class Root extends React.Component {
  constructor(props) {
    super(props);
    const routes = (
      <Route path="/" component={App}>
        <Route component={Dashboard}>
          <IndexRoute component={Home} />
        </Route>
        <Route path="login" component={Login} />
      </Route>
    );
    // some stuff
    }
  }

  requireAuthentication = (nextState, replace) => {
    // stuff
  };

  render() {
    const { store } = this.props;
    return (
      <div>
        <Provider store={store}>
          <Router history={browserHistory} routes={this.routes} />
        </Provider>
      </div>
    );
  }
}

// stuff

export default connect(mapStateToProps, mapDispatchToProps)(Root);

但是现在渲染不好。

如何解决?

最佳答案

渲染方法中 undefined object this.routes

例如,您可以将构造函数中的 const paths = (...); 替换为 this.routes = (...); 以使对象可以在渲染方法。

关于javascript - 在构造函数中定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41901306/

相关文章:

javascript - 我应该为 Electron 应用程序中使用的授权调用使用什么重定向 URI?

javascript - SetTimeout 重定向不适用于 Firefox

javascript - 了解 ReactJS 受控表单组件

javascript - 如何比较两个数组并通过完整迭代删除重复对象

javascript - 如何从复杂的对象数组中获取唯一的对象数组?

javascript - 用一个字符串数组拼接另一个数组?

javascript - 您好,我想让 4 个对象循环从左到右移动,但我的代码不起作用

javascript - 如何在结果中显示我现在拥有的数据?

javascript - 我不断收到 map 不是函数

javascript - React.js,ES6,如何访问ES6类中的react-router Lifecycle?