单 Store 单页应用的状态重置

如果是基于 Redux 等单 Store 形式来构建单页应用,那么需要注意,大多数时候,切换页面时(如前进、后退或直接访问),需要注意状态的重置。

如果用的是 react-router-redux,那么需要在切换后做 reset 的页面的 reducer 中,在 actionLOCATION_CHANGE1 时,返回该 reducer 的 initState。如:

// reducers/page1.js
import { LOCATION_CHANGE } from 'react-router-redux';
import * as actions from '../../actions/page1';

const initialState = {
  list: ['默认文本'],
};

export default function index(state = initialState, action) {
  switch (action.type) {
    case LOCATION_CHANGE:
      return initialState;

    case actions.ADD_TEXT:

      return Object.assign({}, state, {
        list: [action.data, ...state.list],
      });

    default:
      return state;
  }
}

如果用的是 connected-react-router,也类似。

// reducers/counter.js
import { LOCATION_CHANGE } from 'connected-react-router';

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case LOCATION_CHANGE:
      return 0;
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

export default counterReducer

参考