Redux normalizr +处理减少的响应

And*_*gan 5 javascript api-design reactjs redux normalizr

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

我们有很多案例显示数据列表,例如posts已经规范化的数据列表.其中posts列出了API响应被限制在几个关键的领域.

我们还有一些显示其中一个的情况,posts尽管我们现在需要从API中获取具有所有字段的FULL JSON实体.

如何处理这个问题最好?

一个一个单独的减速,形实转换/佐贺,选择和行动?

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

1ve*_*ven 7

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

{
  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',
}
Run Code Online (Sandbox Code Playgroud)

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

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

const POST = new Schema('post');
const POST_ARRAY = arrayOf(POST);
Run Code Online (Sandbox Code Playgroud)

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

// 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),
  });
}
Run Code Online (Sandbox Code Playgroud)

在reducers中,我们需要创建entitiesreducer,它将监听所有操作,如果它有entities有效负载的密钥,则会将此实体添加到app状态:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

我们还需要创建相应的reducers来处理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;
  }
}
Run Code Online (Sandbox Code Playgroud)