redux 中 reducer 的先前状态与 react [英] previous state in reducers in redux with react

查看:60
本文介绍了redux 中 reducer 的先前状态与 react的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的减速器的样子:

Here is what my reducer looks like:

export default function catalogReducer(state = initialState.catalogItems, action){
  switch (action.type) {
    case types.LOAD_CATALOG_SUCCESS:
      return {
         count:action.count,
        products :[...state['products'],
        action.catalogItems  ?
        [...action.catalogItems['products']]
          :
          []
      ]
    default:
      return state;
  }
}

我想做什么:

  1. 这是一个用于加载目录项的 reducer

  1. This is a reducer for loading catalog items

项目来自分页 API.

Items are coming from a paginated api.

问题:

我希望 state 参数应该与之前的状态相关联,但不,它总是从 initialState 获取值,我在应用程序启动时用它来初始化状态.

I was hoping that state argument should would have the previous state associated but no, it is always getting value from initialState which what I initialize the state with on application startup.

这是为什么?有什么办法解决它?

Why is that? What is the way around for it?

基本上,我需要通过分页 API 返回完整的项目集,而不仅仅是 products 数组中给定页面的产品.我最终得到的只是来自上次 api 调用的产品数组,因为 state.products 总是被初始化为一个空数组

Basically I need to have the complete set of items returned through pagination api and not just the products for a given page in products array. What I am ending up with is just the array of products from last api call as state.products always gets initialized as an empty array

此外,一般来说,我对在 react 和 redux 中处理分页 api 感到非常困惑,无法找到一个简单的例子.

Also, generally speaking I am very confused about dealing with pagination api in react and redux and am not able to find a straightforward example.

如果有指导,我们将不胜感激.

A direction would be appreciated.

这是initialState.js 文件的样子:

This is what initialState.js file looks like:

import cookie from 'react-cookie';

export default {
 categories:[],
  sessionId: cookie.load('sessionId') || '',
  youMayLikeItems : [],
  catalogItems: {'products': []}
}

//这个文件是为了集中初始化store中的状态

//This file is to centralize initialization of states in the store

推荐答案

基本上,你需要记住你不应该改变状态.

Basically, you need to remember that you shouldn't mutate state.

export default function catalogReducer(state = initialState, action) {
  switch (action.type) {
    case types.LOAD_CATALOG_SUCCESS:
      return {
        ...state,
        catalogItems: {
          count: action.count,                          
          products: [
            ...state.catalogItems['products'],
            action.catalogItems  ?
              action.catalogItems['products']
              :
              {}
          ]
        }
  default:
    return state;
  }
}

您可以在此处

此外,最好制作没有深层对象的简单状态(docs)使用 Immutable.js

Also it's better to make simple states (docs) without deep objects and use Immutable.js

这篇关于redux 中 reducer 的先前状态与 react的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆