javascript - Redux normalizr + 处理减少的响应

标签 javascript reactjs redux api-design normalizr

Normalizr 非常擅长创建实体的结构化 JSON 存储库。

我们有很多案例显示数据列表,例如posts 已规范化。在列出 posts 的地方,API 响应仅限于几个关键字段。

尽管我们现在需要从 API 中获取包含所有字段的完整 JSON 实体,但我们也有显示这些 posts 之一的情况。

如何最好地处理这个问题?

一个一个单独的 reducer、thunk/saga、选择器和 Action ?

B 只需将从 API 获取的 post 的扩展版本插入到 reducer 中。重用之前的选择器等?

最佳答案

将应用程序的状态视为数据库。我建议你使用这个状态形状:

{
  entities: {
    // List of normalized posts without any nesting. No matter whether they have all fields or not.
    posts: {
      '1': {
        id: '1',
        title: 'Post 1',
      },
      '2': {
        id: '2',
        title: 'Post 2',
      }
    },
  },
  // Ids of posts, which need to displayed.
  posts: ['1', '2'],
  // Id of full post.
  post: '2',
}

首先,我们正在创建我们的 normalizr 模式:

// schemas.js
import { Schema, arrayOf } from 'normalizr';

const POST = new Schema('post');
const POST_ARRAY = arrayOf(POST);

成功响应后,我们正在规范化响应数据并调度操作:

// actions.js/sagas.js
function handlePostsResponse(body) {
  dispatch({
    type: 'FETCH_POSTS',
    payload: normalize(body.result, POST_ARRAY),
  });
}

function handleFullPostResponse(body) {
  dispatch({
    type: 'FETCH_FULL_POST',
    payload: normalize(body.result, POST),
  });
}

在 reducer 中,我们需要创建 entities reducer,它会监听所有的 Action ,如果它在 payload 中有 entities 键,就会将这个实体添加到应用程序状态:

// reducers.js
import merge from 'lodash/merge';

function entities(state = {}, action) {
  const payload = action.payload;

  if (payload && payload.entities) {
    return merge({}, state, payload.entities);
  }

  return state;
}

我们还需要创建相应的 reducer 来处理 FETCH_BOARDSFETCH_FULL_BOARD 操作:

// Posts reducer will be storing only posts ids.
function posts(state = [], action) {
  switch (action.type) {
    case 'FETCH_POSTS':
      // Post id is stored in `result` variable of normalizr output.
      return [...state, action.payload.result];
    default:
      return state;
  }
}

// Post reducer will be storing current post id.
// Further, you can replace `state` variable by object and store `isFetching` and other variables.
function post(state = null, action) {
  switch (action.type) {
    case 'FETCH_FULL_POST':
      return action.payload.id;
    default:
      return state;
  }
}

关于javascript - Redux normalizr + 处理减少的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137381/

相关文章:

javascript - 用于搜索框的 jQuery 滑动条?

javascript - ReactJS 问题 : () => vs function ()

javascript - 为什么 React-router Link 不起作用(ReactJS + Redux)?

javascript - 如何使用 Underscore.js 对数组的数组执行并集或交集

javascript - 在 react-native 中测试 TextInput 组件

javascript - 无法将 Prop 从父组件传递到子组件

reactjs - 通量多个存储实例

javascript - rc-calendar 显示内部 react 组件

reactjs - 你应该如何使用 flowtype redux thunk ?

javascript - Angular 观察指令中 $http.pendingRequests 的变化