首页 > 解决方案 > react router中使用history.push()时需要刷新的问题

问题描述

我现在想在 redux 上登录成功时移动页面。我发现的方法是使用createBrowserHistory(). 所以我实现了它。然后使用临时的history.push ("/Dashboard");. 它会更改url浏览器的 ,但除非用户刷新它,否则它不会移动。我曾经createBrowserHistory ({forceRefresh: true})解决过这个问题。但这会刷新页面。(屏幕会闪烁。)我无法更改 webpack 的设置,因为我使用了 CRA。当我试图解决这个问题时我该怎么办?

历史.js

import { createBrowserHistory } from "history";

// export default createBrowserHistory({ forceRefresh: true });
export default createBrowserHistory();

index.js

/* import other modules... */
import { BrowserRouter as Router } from "react-router-dom";
import history from "./utils/history";

const logger = createLogger();
const sagaMiddleware = createSagaMiddleware({
  context: { history: history },
}); 

const store = createStore(
  rootReducer,
  composeWithDevTools(
    applyMiddleware(
      sagaMiddleware, 
      logger
    )
  )
);
sagaMiddleware.run(rootSaga); 
ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,
  document.getElementById("root")
);

还原

/* import other modules... */
import history from "../utils/history";

/* code ... */
// redux-saga
export function* login(user) {
  try {
    const res = yield call(apiClient, {
      url: "/login",
      method: "post",
      data: user,
      timeout: 4000,
    });
    console.log(res);
  
    history.push("/Dashboard");
    yield put({
      type: LOGIN_SUCCESS,
      user: user, 
    });
  } catch (error) {
    console.error(error);
    yield put({
      type: LOGIN_ERROR,
      error: true,
    });
  }

应用程序.js

function App() {
  return (
    <div className="App">
      <Switch>
        <AuthRoute path="/Dashboard/:id" component={Dashboard} />
        <AuthRoute exact={true} path="/Dashboard" component={Dashboard} />
        <Route path="/" component={LoginPage} />
        <Route path="/Loginpage" component={LoginPage} />
      </Switch>
    </div>
  );
}

仪表板.js

function Dashboard(props) {
  let location = useLocation();
  console.log(location.pathname);
  const tableRender = () => {
    switch (location.pathname) {
      case "/case1": // pathname
        return <CommonTable />;
      case "/case2":
        return <CommonTable2 />;
    }
  };
  // const user = useSelector((state) => state.loginReducer.user, []);

  return (
    <>
      <GlobalHead />
      <Layout>
        <GlobalSide />
        <LocalSide />
        <Layout className="site-layout">
          <Content style={{ margin: "0 16px" }}>
            <SubHeader />
            <div className="Content-area">{tableRender()}</div>
          </Content>
          <GlobalFooter />
        </Layout>
      </Layout>
    </>
  );
}

export default Dashboard;

标签: reactjsreduxredux-saga

解决方案


加载您的代码框并运行它后,控制台中会出现一条警告,立即说明问题所在。

警告:<BrowserRouter>忽略历史道具。要使用自定义历史记录,请使用import { Router }而不是import { BrowserRouter as Router }.

解决方案是简单地使用Router而不是BrowserRouterin index.js

import { Router } from "react-router-dom"; // <-- import Router
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import rootReducer, { rootSaga } from "./modules/index";
import history from "./utils/history";

const sagaMiddleware = createSagaMiddleware({
  context: { history: history }
});

const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,
  rootElement
);

编辑问题-需要-被刷新-when-using-history-push-in-react-router


推荐阅读