【问题标题】:react-router-dom: history does not reload (render) page automaticallyreact-router-dom:历史不会自动重新加载(渲染)页面
【发布时间】:2020-12-10 10:46:36
【问题描述】:

我正在使用 redux、redux-saga 以及其他依赖项,我在登录后尝试使用 history.push() 重定向页面,但它不起作用。所以,为了解决这个问题,我在那之后使用了 window.location.reload()。

这是我的代码的一部分:

export function* signIn({ payload }) {
  try {
    const { email, password } = payload;
  
    const response = yield call(api.post, 'sessions', {
      email,
      password
    });

    const { token, user } = response.data;

    yield put(signInSuccess(token, user));

    history.push('/home');
    window.location.reload();
  } catch(err) {
    yield put(signFailure());
  }
}

还有我的 App.js:

export default function App() {
  return (
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <Router history={history}>
          <Routes />
          <ToastContainer autoClose={4000}/>
        </Router>
      </PersistGate>
    </Provider>
  );
}

为什么会这样?我读到这是因为在最近版本的路由器/历史中,历史没有像以前那样工作,它不会自动重定向,我不知道,我想我是这么理解的。

有人知道如何解决这个问题吗?不必每次都使用 window.location.reload()?

对不起我的英语,我来自巴西。

【问题讨论】:

    标签: javascript reactjs redux react-redux react-router-dom


    【解决方案1】:

    你没有在你的 signIn saga 中使用 React Router history,所以它不会使用路由器重定向。由于 saga 无法做到这一点,因此您必须将其移至调用 signIn 的组件中。

    我通常给signIn添加一个回调,在调用signIn的组件内部,调用成功后可以用history重定向。

    【讨论】:

      猜你喜欢
      • 2022-07-28
      • 1970-01-01
      • 2018-12-06
      • 2022-12-17
      • 2023-03-08
      • 2020-09-04
      • 2021-01-11
      • 2016-08-21
      相关资源
      最近更新 更多