【发布时间】:2020-02-04 08:48:15
【问题描述】:
最近开始对 API 响应进行规范化,以使其更加扁平化。 我已经设法从这个
平展 API 响应到这里:
case FETCH_IMAGES_SUCCESS:
console.log(action.images.entities)
如何迭代它?
之前我使用this.props.images.map(),但现在数据是分开的。
我应该怎么做才能用相应的嵌套数据迭代图像数组?
Reducer.js
import {
UPLOAD_IMAGE_SUCCESS,
POST_COMMENT_SUCCESS,
DELETE_IMAGE_FAILURE,
FETCH_IMAGES_SUCCESS,
POST_COMMENT,
POST_LIKE,
POST_LIKE_SUCCESS,
DISLIKE_POST_SUCCESS,
DELETE_IMAGE_SUCCESS,
} from '../types';
import { REHYDRATE, PURGE, FLUSH }from 'redux-persist'
// We use seamless-immutable but thats for
const initialState = {
images: [],
likeCount: [],
liked: false
};
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_IMAGES_SUCCESS:
console.log(action.images.entities)
// return {
// ...state,
// images: action.images.entities.images,
// ...state.images
// };
default:
return state;
}
};
saga.js
import { normalize, schema } from "normalizr";
import {imageListSchema} from "../schemas";
export function* getImages() {
try {
const images = yield call(api.images.fetchImages);
// debugger;
// console.log(normalize(images, [imageSchema]));
// console.log(images)
const data = normalize(images, imageListSchema )
yield put(fetchImagesSuccess(data));
} catch (error) {
yield put(fetchImageFailure(error.response));
}
}
【问题讨论】:
-
Object.keys()或Object.values()? -
它似乎不对齐。这看起来很老套。我在想类似redux.js.org/recipes/structuring-reducers/… 的东西,比如postsById 等。但不知道如何解决这个问题。
标签: reactjs redux react-redux normalizr