【问题标题】:Redux - reset stateRedux - 重置状态
【发布时间】:2017-10-16 10:56:18
【问题描述】:

我正在尝试根据 Dan Abramov here 的建议实施 redux 重置状态操作。我已经像这样设置了我的减速器和存储:

Index.js:

import {applyMiddleware,createStore} from 'redux';
import combineReducers from './reducers/index';
import {wrapStore,alias} from 'react-chrome-redux';
import thunk from 'redux-thunk';
import aliases from './aliases/aliases';

const combineAppReducers = ( state, action ) => {
  if ( action.type === 'LOG_OUT' ) {
    state = undefined;
  }

  return combineReducers(state, action)
}

const middlewares = [alias(aliases), thunk];

const store = createStore(combineAppReducers,applyMiddleware(...middlewares));

wrapStore(store, {
  portName: 'example'
});

Reducers.js:

import {combineReducers} from 'redux';
import userAuthReducer from './userAuthReducer';
import manageTeamsReducer from './manageTeamsReducer';

function lastAction(state = null, action) {
  return action;
}

export default combineReducers({
  userAuthReducer,manageTeamsReducer,lastAction
});

看起来我已经正确设置了一切,但应用程序没有重置状态,有人能发现我哪里出错了吗?

这是我更密切关注的另一篇文章:

https://medium.com/@agungsantoso/how-to-reset-the-state-of-a-redux-store-7f9d85b190bc

【问题讨论】:

  • 您是否尝试过将状态设置为空对象?喜欢state = {}
  • 还有什么错误?
  • 我认为这不是最好的方法,但是,您可以将您的状态恢复为其第一个值调度:@@INIT 操作。
  • 不幸的是,它是一个 chrome 扩展,所以它并不总是吐出错误。我应该在哪里将状态设置为空对象?
  • 我不能,因为此时应用程序编译时出现错误

标签: javascript reactjs redux react-redux


【解决方案1】:

工作正常。 你可以查看我的sn-p。 可以上传错误日志吗?

function lastAction(state = null, action) {
  return action;
}

function counter(state = 0, action) {
  if ( action.type === 'INC' ) {
      return state+1;
  }
 
  return state;
}

const  combineAppReducers = Redux.combineReducers({
  lastAction,
  counter
});

const combineReducers = ( state, action ) => {
  if ( action.type === 'LOG_OUT' ) {
    state = undefined;
  }
  return combineAppReducers(state, action)
}

const store = Redux.createStore(combineReducers);

const root = document.createElement('ul');
document.body.append(root);
let unsubscribe = store.subscribe(() =>{
  const li = document.createElement('li');
  li.append(store.getState().counter);
  root.append(li);
})

store.dispatch({type: 'INC'});
store.dispatch({type: 'INC'});
store.dispatch({type: 'INC'});
store.dispatch({type: 'LOG_OUT'});
store.dispatch({type: 'INC'});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.js"></script>
</head>
<body>
</body>
</html>

【讨论】:

  • 我得到了要编译的代码(上面已经编辑过)。我的操作都按照新集成的方式工作,但注销操作仍然不会重置状态...
猜你喜欢
  • 2020-12-14
  • 2019-06-09
  • 1970-01-01
  • 2023-01-27
  • 2018-05-03
  • 2020-04-12
  • 2016-06-07
  • 2021-07-22
相关资源
最近更新 更多