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

问题描述 投票:0回答:2

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

MyProfile.js

  handleProfileUpdate = () => {
    let user = this.state;
    this.props.updateUserProfile(user);
  }

行动定义如下

export const updateUserProfile = (obj) => ({
  type: types.USER_PROFILE_UPDATE_REQUEST,
  payload: obj
});

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()
  ]);
}

但代码产量put(push('/ dashboard'))不会重定向到页面。

有关如何解决此问题的任何想法?

reactjs redux-saga
2个回答
0
投票

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

history.js

import createHistory from 'history/createBrowserHistory';
const history = createHistory();
export default history;

将历史文件导入到saga中

import history from '../../history';

修改观察者传奇如下。

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);
  }
}

现在,您需要定义forwardTo函数,如下所示。

function forwardTo(location) {
  history.push(location);
}

0
投票

您需要将历史记录对象推送到其他路径。

  1. 如果您可以在操作中传递历史对象,则可以直接编写history.push('/ dashboard')。
  2. 您在调用操作的操作中传递回调函数,并使用yield put(callback())调用该回调函数,以便您可以使用第1点中提到的相同命令重定向。
  3. window.location.href ='dashboard';
© www.soinside.com 2019 - 2024. All rights reserved.