成功操作后重定向到特定页面 - Redux saga

pra*_*esh 1 reactjs redux-saga

我有一个用户个人资料页面,用户可以在其中更新数据。提交数据后,应将其重定向到仪表板页面。

我的配置文件

  handleProfileUpdate = () => {
    let user = this.state;
    this.props.updateUserProfile(user);
  }
Run Code Online (Sandbox Code Playgroud)

动作定义如下

export const updateUserProfile = (obj) => ({
  type: types.USER_PROFILE_UPDATE_REQUEST,
  payload: obj
});
Run Code Online (Sandbox Code Playgroud)

Saga 文件定义如下。

function* updateUserProfile(action) {
  try {
    let data = action.payload;
    yield call(userProvider.updateUserProfile, data);

    // dispatch a success action to the store
    yield put({ type: types.USER_PROFILE_UPDATE_SUCCESS, data });
    yield put(push('/dashboard'));
    yield put(constants.successMsg(userProfileUpdateSuccess));

  } catch (error) {
    // dispatch a failure action to the store with the error
    yield put(constants.DEFAULT_ERROR_MSG);
  }
}

export function* watchUserProfileUpdateRequest() {
  yield takeLatest(types.USER_PROFILE_UPDATE_REQUEST, updateUserProfile);
}


export default function* userSaga() {
  yield all([
    watchUserProfileRequest(),
    watchUserProfileUpdateRequest()
  ]);
}
Run Code Online (Sandbox Code Playgroud)

但是代码yield put(push('/dashboard'))没有重定向到页面。

关于如何解决这个问题的任何想法?

pra*_*esh 6

我自己建立了一个解决方案

历史.js

import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export default history;
Run Code Online (Sandbox Code Playgroud)

将历史文件导入 saga

import history from '../../history';
Run Code Online (Sandbox Code Playgroud)

修改 watcher saga 如下。

function* updateUserProfile(action) {
  try {
    let data = action.payload;
    yield call(userProvider.updateUserProfile, data);

    // dispatch a success action to the store
    yield put({ type: types.USER_PROFILE_UPDATE_SUCCESS, data });
    yield call(forwardTo, '/dashboard');
    yield put(constants.successMsg(userProfileUpdateSuccess));

  } catch (error) {
    // dispatch a failure action to the store with the error
    yield put(constants.DEFAULT_ERROR_MSG);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,您需要按如下方式定义 forwardTo 函数。

function forwardTo(location) {
  history.push(location);
}
Run Code Online (Sandbox Code Playgroud)