데이터베이스의 앱 상태를 생각해보십시오. 우리는 응답 데이터를 정상화하고 작업을 파견하는 성공 응답 후
// schemas.js
import { Schema, arrayOf } from 'normalizr';
const POST = new Schema('post');
const POST_ARRAY = arrayOf(POST);
: 우리는 우리의 normalizr
스키마를 작성하는 모든
{
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',
}
첫째, 나는 당신이이 상태 모양을 사용하는 것이 좋습니다
// 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),
});
}
감속기에서는 entities
감속기를 만들어야 모든 작업을 청취 할 수 있으며 지불 할 금액은 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;
}
는 또한 우리는 감속기가 FETCH_BOARDS
및 FETCH_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;
}
}
질문이 있습니다. '병합 ({}, 상태, payload.entities);'상태를 변경 하시겠습니까? – Daskus
@Daskus 아니요. 빈 객체를 첫 번째 인수로 전달할 때 merge 함수가 새 객체를 반환합니다. – 1ven
이것은 가장 좋은 대답입니다. 우리는이 접근법을 위해 정확하게 끝을 맺었습니다. 열쇠는 훌륭한 셀렉터와 필터를 작성하는 데 있습니다. 또한 Immutable JS를 사용하는 것이 좋습니다 ...! – AndrewMcLagan