来自 Reducer 的调用操作

Call action from Reducer

我有应用程序,它从我的服务器加载数据。我从我的索引文件中调度 getData() 操作。我有几个减速器,与 combineReducers 一起加入 rootReducer。

我确实通过 getData 获取数据。但是如何调度 SET_DATA 动作,或者简单地用新数据改变状态?

我无法从 reducer 调用 store.dispatch 并按照我当前的方式调用操作,它会更改我状态下的数据,但不会重绘页面。

import { SYSTEM_FILTER, SET_DATA, GET_DATA, getData, setData } from '../actions/systemlist'
import rootReducer from './index'

const initialState = {
      systemFilters: true,
      systems: []
    };
export default function systemlist(state=initialState, action) {
  switch (action.type) {
    case SYSTEM_FILTER:
       var enabled=document.getElementById("filterSystems").checked;
       return {systemFilters: enabled, systems: state.systems}
    case GET_DATA:
       console.log("Getting data");
       $.getJSON("../data/systems.json", function(data) {
          data=data.sort(function(a, b) {
             var textA = a.name.toUpperCase();
             var textB = b.name.toUpperCase();
             return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
          });
          systemlist(state, {type: "SET_DATA", data: data});
       });
       return state
    case SET_DATA:
       console.log("Setting data");
       $("#systemsMenuCounter").html(action.data.length);
       return {systemFilters: state.systemFilters, systems: action.data}
    default:
      return state
  }
}

首先,你的 reducer 函数应该是纯函数。那是什么意思? The redux documentation says:

For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

这里不多说,关于redux结合异步请求的问题,给大家举两个中间件的例子,主要解决异步问题

  1. Thunk 解决了 return 函数执行条件调度的动作创建者的问题。
  2. Sagas 使用生成器函数进行链接操作

还有其他几种方法可以解决您的问题,但我还没有提到,但我推荐 Redux Documentation (Async Actions) 作为起点!