【问题标题】:pushing history according to previously selected filters from localstorage根据本地存储中先前选择的过滤器推送历史记录
【发布时间】:2021-08-19 08:32:04
【问题描述】:

由于我是 React 新手,我正在尝试根据存储在本地存储中的先前选择的过滤器正确实现路由,然后在应用程序启动时将它们推送到历史记录(超时)。

如果没有超时,应用会在获取用户上下文/令牌身份验证之间跳转

http://localhost:3000/#tokenid=123456789012345678901234567890

以及我想路由到的实际 URL:

http://localhost:3000/monthly?date=1629361313861&dispatcher=Srv+DE+01

由于我不知道这是否是正确的方法,而且由于 UserContext 尚未建立,它会“跳跃”,因此我非常感谢任何关于我遇到的这个问题的建议。

App.tsx

import React from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import { Switch, Route } from 'react-router-dom';
import { CssBaseline } from '@material-ui/core';
import { ToastContainer } from 'react-toastify';
import { MuiPickersUtilsProvider } from '@material-ui/pickers';
import DateFnsUtils from '@date-io/date-fns';
import 'react-toastify/dist/ReactToastify.css';

import store from './services';
import history from './utils/history';
import './i18n';

import UserContext from './modules/UserContext';
import FactBox from './modules/FactBox';
import ModalRoot from './components/ModalRoot';
import pathsConst from './const/paths';
import DailyView from './pages/DailyView';
import WeeklyView from './pages/WeeklyView';
import MonthlyView from './pages/MonthlyView';
import NotFound from './pages/404';

const App = () => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <CssBaseline />
        <UserContext>
          <Switch>
            <Route exact path={pathsConst.INDEX} component={DailyView} />
            <Route exact path={pathsConst.WEEKLY_VIEW} component={WeeklyView} />
            <Route exact path={pathsConst.MONTHLY_VIEW} component={MonthlyView} />
            <Route component={NotFound} />
          </Switch>

          <FactBox />
          <ModalRoot />
        </UserContext>

      </MuiPickersUtilsProvider>
    </ConnectedRouter>

    <ToastContainer
      position="bottom-center"
      autoClose={6000}
      hideProgressBar
      pauseOnHover
    />
  </Provider>
);

export default App;

reducer.ts

import { combineReducers } from 'redux';
import { connectRouter as router } from 'connected-react-router';

import history from '../utils/history';
import loading from './loading/reducer';
import modal from './modal/reducer';
import resources from './resources/reducer';
import departments from './departments/reducer';
import dispatchers from './dispatchers/reducer';
import projects from './projects/reducer';
import events from './events/reducer';
import uiSettings from './uiSettings/reducer';
import userContext from './userContext/reducer';
import holidays from './holidays/reducer';

const rootReducer = combineReducers({
  router: router(history),
  loading,
  modal,
  resources,
  departments,
  dispatchers,
  projects,
  events,
  uiSettings,
  userContext,
  holidays,
});

export default rootReducer;

/utils/history.ts

import { createBrowserHistory } from 'history';
import pathsConst from '../const/paths';

function getHistory () {
  let history = createBrowserHistory({
    basename: process.env.PUBLIC_URL,
  });
  let lastPath = '/';
  let lastQueryString = localStorage.getItem("lastQueryString");
  let lastPathTemp = localStorage.getItem("lastPath");
  let lastURL = localStorage.getItem("lastURL");
  let adalID = localStorage.getItem("adal.idtoken");
  if ( lastPathTemp !== null ) {
    if (lastPathTemp.includes('weekly')=== true) {
      lastPath = pathsConst.WEEKLY_VIEW;
    }
    else if (lastPathTemp.includes('monthly')=== true) {
      lastPath = pathsConst.MONTHLY_VIEW;
    }
    else {
      lastPath = pathsConst.INDEX;
    }
  } 

  // DBG: 
  console.log('DBG - LAST QUERY STRING:', lastQueryString);
  console.log('DBG - LAST URL:', lastURL);

  if ( lastQueryString !== null && lastPath !== null && adalID !== null  ) { 

    let lastQueryStringEdit = "?date=" + Date.now();
    // INFO: Check for additional query params
    if (lastQueryString.indexOf("&") !== -1) {
      let pos1 = lastQueryString.indexOf("&");
      let substr = lastQueryString.substring(pos1, lastQueryString.length);
      lastQueryStringEdit = "?date=" + Date.now() + substr;
    } 

      setTimeout(function() {
      console.log('DBG - PUSHING.............................');
      history.push({
      pathname: lastPath,
      search: lastQueryStringEdit
      });
      }, 2000);

    return history;

  }
  else { // INFO: Return as is

    return history;

  }
}

const history  = getHistory();

export default history;

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    这是我访问 url 属性的方式

    //for accessing path of url
    const {pathname} = useLocation();
    

    ...

    //for going back to the last used url
    const navigate = useNavigate(); //react router v6
    navigate(-1) // to go back to last used url
    navigate(-2) // go back to second last used url
    navigate(-3) // so on ...
    

    ... 为了在 url 中搜索特定参数,我制作了一个自定义钩子,如下所示,并传入我想要获取值的所需变量名称

    import { useLocation } from "react-router-dom";
    
    export default function useGetParameter(name: string) {
      const { search } = useLocation();
      const query = new URLSearchParams(search);
      return query.get(name);
    }
    //this custom hook return the required param in url or null if it does not exist
    

    推荐

    我建议不要以这种方式将值存储在 localstorage 中,因为 localstorage 值没有过期时间,您必须从浏览器中显式删除它们。利用会话存储与例如(useState、this.state、useContext、Redux 等)来存储和访问变量属性。但是,如果您在任何情况下仍希望将数据保存在 localstorage 上更长的时间,那么我建议您使用其他可以为您完成这项工作的库。好处是,这些库被配置为更具约束力并为您提供逻辑分离。请关注redux persist

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多