redux saga and history.push

落花浮王杯 提交于 2019-12-04 08:36:17

I usually handle conditional navigation like that in the saga.

The simplest answer with the existing code is to pass a history object as a prop in the SUBMIT_USERNAME_PASSWORD action and do the history.push() call in the success case of the saga, something like:

const onSubmitClick = ({username, password}) => {
  const { history } = this.props;

  return {
    type: SUBMIT_USERNAME_PASSWORD,
    payload: {username, password, history}
  };
};

.......

function* shootAPI(action){
  try{
    const res = yield call(shootApiTokenAuth, action.payload);
    const { history } = action.payload;

    yield put({
      type: REQUEST_SUCCESS,
      payload: res
    });

    history.push('/companies');
  }catch(err){
    yield put({
      type: REQUEST_FAILED,
      payload: err
    });
  }
}

I am not as experienced in react but you could achieve it as follows:

1.Create a new Module: history-wrapper.ts

export class HistoryWrapper {
  static history;
  static init(history){
    HistoryWrapper.history = history;
  }
}

2.In you login.jsx

  HistoryWrapper.init(history);//initialize history in HistoryWrapper

3.Subsequently anywhere in your app

  HistoryWrapper.history.push('/whatever');

React has additional lifecycle. I just know it today. They are many of them.

componentDidUpdate() {
    this.props.history.push('/companies');
  }
yield put(push('/path-to-go'));

solved my problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!