【问题标题】:Redux - Combining multiple reducers result in state clearingRedux - 组合多个 reducer 导致状态清除
【发布时间】:2017-06-04 00:06:45
【问题描述】:

对 redux 相当陌生,并且已经阅读了官方指南。现在我正在尝试独自做一些事情。我有两个减速器,并且正在使用 react-thunk。当我在第一个动作之后调度一个动作时,它会清除我的另一个减速器的集合。为了说明我的意思是我有:

Actions.js

import axios from 'axios';

function fetchAtms() {
  return axios.get('http://localhost:4567');
}

export const recievedAtms = (atms) => {
  return {
    type: 'RECIEVED_ATMS',
    atms
  }
}

export const completed = () => {
  return {
    type: 'COMPLETED',
  }
}

export const loadMore = () => {
  return {
    type: 'LOAD_MORE',
  }
}

export const loadAtms = (forPerson) => {
  return function (dispatch) {
    return fetchAtms().then((response) => {
      let atms = response.data.map((item) => {return item['location']})
      dispatch(recievedAtms(atms));
      // When dispatch(completed()); is called
      // it is clears my app collection.
      dispatch(completed());
      // $r.store.getState() => Object {app: {atms: []}, isLoading: false, router: Object}
    }, (error) => {
        console.log('implement me');
    })
  }
}

减速器

import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

const app = (state = {}, action) => {
  switch (action.type) {
    case 'RECIEVED_ATMS':
      return {
        atms: action.atms
      }
    default:
      return {};
  }
}

const isLoading = (state = true, action) => {
  switch (action.type) {
    case 'COMPLETED':
      return !state;
    default:
      return state;
  }
}

const appReducer = combineReducers({
  app,
  isLoading,
  router: routerReducer
});

export default appReducer;

Store.js

import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware} from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import thunk from 'redux-thunk';

import appReducer from './reducers/app';

export const history = createHistory()

const middleware = routerMiddleware(history);

const store = createStore(appReducer, applyMiddleware(middleware, thunk));

export default store;

如果您在Actions.js 中磨练loadAtms 函数I:

  1. 取我的自动取款机
  2. 派送收到的Atms
  3. 发货完成

当我发送 completed() 时,它会清除我的 atms 集合。我不完全确定。我不希望这样,因为两个减速器之间的状态是分开的。我的期望是:

在我解雇completed() 之后,我不希望它清除我的自动取款机集合。调用completed() 后的结果状态应如下所示:

{
  isLoading: false,
  app: {atms: [{id: 1}, {id: 2}, {id: 3}]}
}

目前正在发生的事情是这样的:

{isLoading: false, app: {}} 

关于我在这里可能做错了什么的任何想法。

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    如果操作不是它正在寻找的操作,您的 atms 减速器将返回 {}。相反,我相信你应该返回state。所以:

    const app = (state = {}, action) => {
      switch (action.type) {
        case 'RECIEVED_ATMS':
          return {
            atms: action.atms
          }
        default:
          return state;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2019-07-28
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多