【问题标题】:Store browserHistory using history.js in react redux architecture with SSR使用 history.js 在 React Redux 架构中使用 SSR 存储 browserHistory
【发布时间】:2016-06-24 11:51:04
【问题描述】:

如何保存访问 SSR react-redux 应用的用户的完整路由器历史记录?我试过修改 react-redux-router 包的 reducer.js 文件……但是当用户通过 SSR 加载时,历史数组被重置。

/**
 * This action type will be dispatched when your history
* receives a location change.
   */
export const LOCATION_CHANGE = '@@router/LOCATION_CHANGE'

 const initialState = {
    locationBeforeTransitions: null,
    locationHistory: []
}

/**
 * This reducer will update the state with the most recent location history 
 * has transitioned to. This may not be in sync with the router,     particularly
 * if you have asynchronously-loaded routes, so reading from and relying on
 * this state is discouraged.
 */
 export function routerReducer(state = initialState, { type, payload } = {})         {
 if (type === LOCATION_CHANGE) {

return { ...state,
  locationBeforeTransitions: payload,
  locationHistory: state.locationHistory.concat([payload]) }
 }

return state
}

参考:https://github.com/reactjs/react-router-redux/blob/master/src/reducer.js

但是,我认为这应该在中间件中实现

无论如何,这(存储整个以前的会话历史)似乎是一个足够常见的用例,也许有人已经制定了最佳实践。??

也许甚至可以通过没有 react-router-redux 的 react-router 中的 historyjs 对象访问完整的历史记录。

我正在寻找如何在用户关闭浏览器或离开网站时将用户会话的完整历史记录存储在 redux 状态并将其发布到我的 api 服务器的答案。 (如果这不可能,我可以在每次导航时发布它。)然后我想在用户主页上的“最近查看”页面列表中显示此历史记录。

【问题讨论】:

    标签: redux react-router browser-history history.js react-router-redux


    【解决方案1】:

    首先,您不必干预react-redux-router 的内部结构。

    正如您在提供的代码中所见,react-redux-router 导出了一个 LOCATION_CHANGE 操作。

    您可以在自己的 reducer 中使用此操作。这是一个例子:

    // locationHistoryReducer.js
    import { LOCATION_CHANGE } from 'react-router-redux';
    
    export default function locationHistory(state = [], action) {
      if (action.type === LOCATION_CHANGE) {
        return state.concat([action.payload]);
      }
      return state;
    }
    

    但是,这可能是不必要的。您认为可以使用middleware 来实现这一点的假设是正确的。下面是一个中间件层的例子:

    const historySaver = store => next => action => {
      if (action.type === LOCATION_CHANGE) {
        // Do whatever you wish with action.payload
        // Send it an HTTP request to the server, save it in a cookie, localStorage, etc.
      }
      return next(action)
    }
    

    以下是在商店中应用该层的方法:

    let store = createStore(
      combineReducers(reducers),
      applyMiddleware(
        historySaver
      )
    )
    

    现在,如何保存和加载数据完全取决于您(与 react-router 和浏览器的历史无关)。

    在官方文档中,他们推荐 injecting the initial state on the server side 使用 window.__PRELOADED_STATE__ 变量。

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 2017-09-12
      • 2020-10-15
      • 2017-07-10
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      相关资源
      最近更新 更多