react-router重定向componentDidMount不会触发

时间:2018-01-09 20:42:07

标签: reactjs react-router react-redux

我刚刚进入react / redux并且我已经能够成功调用登录api和另一个api来检索软件包列表。成功登录后应调用用于检索软件包列表的API,即,重定向到/ packages路由并从componentDidMount()调用api。重定向有效,但只有在我重新加载页面时才会触发componentDidMount()。重定向和调用api以使用react-router获取软件包的正确方法是什么?

loginReducer.js

import {Map,fromJS,List} from 'immutable';
import * as types from '../actions/actionTypes';
import initialState from './initialState';
import {browserHistory} from 'react-router';

const creds = Map({
  credentials: Map({
    authToken: null,
    details: Map({
      uuid: null,
      emailAddress: null,
      permissions: List(),
      roles: List(),
      firstName: null,
      lastName: null,
      status: null
    }),
    refreshToken: null
  })
});

export default function loginReducer(state = creds.get('credentials'), action) {
  switch (action.type) {
    case types.LOGIN_USER_SUCCESS:
      hashHistory.push('/packages')
      return state;
    default:
      return state;
  }
}

Packages.jsx

import React, {PropTypes} from 'react';
import pureRender from 'pure-render-decorator';
import {connect} from 'react-redux';
import {loadPackages} from '../../actions/packageActions';
import reducer from '../../reducers/rootReducer';
import PackageList from './PackageList';

export class Packages extends React.Component {
  componentDidMount() {
    console.log('loading packages'); // EDIT
    this.props.dispatch(loadPackages());
  }
  render() {
    return (
      <div className="col-lg-12">
        {this.props.results ?
        <PackageList results={this.props.results} /> :
        <h3>No Packages Available</h3>}
      </div>
    );
  }
};

const mapStateToProps = (state, ownProps) => {
  return {
    packages: state.packages.get('packages'),
    results: state.packages.getIn(['packages','results'])
  };
}

export const PackagesContainer = connect(mapStateToProps)(Packages);

index.jsx

const routes = <Route component={App}>
  <Route path="/packages" component={PackagesContainer} />
  <Route path="/login" component={LoginContainer} />
</Route>;

ReactDOM.render(
  <Provider store={store}>
    <Router history={hashHistory}>{routes}</Router>
  </Provider>,
  document.getElementById('app')
);

1 个答案:

答案 0 :(得分:0)

当我在路由器定义中使用hashHistory时,我正在使用browserHistory.push()进行重定向。