在页面转换时清除一个redux状态

时间:2016-04-14 06:01:05

标签: reactjs react-router redux

我正在创建这样的通知状态(在redux中),

import { STORE_NOTIF, PURGE_NOTIF } from '../actions/notif';

const defaultState = {
  kind: null,
  message: null
}

export default function notifReducer(state = defaultState, action) {
  switch(action.type) {
  case STORE_NOTIF:
    return {kind: action.kind, message: action.message};
  case PURGE_NOTIF:
    return defaultState;
  default:
    return state;
  }
}

这适用于我知道要控制的事件。但是,当我转换到页面时,我应该在哪里实施清算(PURGE_NOTIF),比如从登录到主页?我不想在每个组件上写一个componentWillMount(我不认为这是写方式)来清除notifState。这应该像路线中的某个地方一样吗?我使用react-router BTW。

更新,回答

我的新reducer看起来像这样,我添加了displayed布尔值

import _ from 'lodash';

import { STORE_NOTIF, PURGE_NOTIF, DISPLAY_NOTIF } from '../actions/notif';

const defaultState = {
  kind: null,
  message: null,
  displayed: true
}

export default function notifReducer(state = defaultState, action) {
  switch(action.type) {
  case STORE_NOTIF:
    return _.merge({}, state, { kind: action.kind, message: action.message, displayed: action.displayImmediately });
  case DISPLAY_NOTIF:
    return _.merge({}, state, { displayed: true });
  case PURGE_NOTIF:
    return defaultState;
  default:
    return state;
  }
}

在我的客户端,我检查它是否已经显示并正确处理。

const scrollTop = () => { window.scrollTo(0, 0) }
const handleNotifs = (store) => {
  const notifState = store.getState().notifState;

  if (notifState.message) {
    if (notifState.displayed) {
      store.dispatch({type: PURGE_NOTIF});
    } else {
      store.dispatch({type: DISPLAY_NOTIF});
    }
  }
}

const store = applyMiddleware(...middlewares)(createStore)(reducer, initialState);

ReactDOM.render(
  <Provider store={store}>
    <Router onUpdate={() => {scrollTop(); handleNotifs(store)}} routes={routes} history={browserHistory} />
  </Provider>,
  document.getElementById('app')
);

1 个答案:

答案 0 :(得分:2)

如果使用普通路由对象定义React路由器路由,则可以在路由上定义生命周期事件。实现所描述内容的最简单方法是在路径上指定onLeave

const onLeave = () => store.dispatch({type: "PURGE_NOTIF"})
const routes = (
  {path: "/login", component: LoginPage, onLeave}
)

您需要将store的引用传递给routes。这是一个可能的解决方案:

// index.js
const store = createStore(/* ... */)
const routes = createRoutes(store)

ReactDOM.render(
  <Provider store={store}>
    <Router routes={routes} />
  </Provider>
)

// createRoutes.js
export default store => {
  const purge = () => store.dispatch({type: "PURGE_NOTIF"})

  return (
    {path: "/", component: Application, childRoutes: [
      {path: "login", component: LoginPage, onLeave: purge},
      {path: "dashboard", component: Dashboard},
    ]}
  )
}