【问题标题】:How do I return an array in the reducer?如何在减速器中返回一个数组?
【发布时间】:2021-01-29 22:56:10
【问题描述】:

我正在制作一个应用程序,我需要将板作为数组返回以在 Home 组件中进行映射

应用程序状态(应该)是这样的:

{
boardsList: {
    boards: An array of retrieved boards  
    boardCount: their length
    ...other stuff related to boards
},

boardList 缩减器:


import {
    HOME_PAGE_LOADED,
    CHECK_IF_BOARD
} from '../constants/actiontypes'


const boards = (state = {}, action) => {

    switch (action.type) {
        case HOME_PAGE_LOADED:
            return {
                ...state,
                boards: action.payload.boards
            }
        default:
            return state
    }
}


export default boards;

动作负载:

payload:

boardCount: 2
boards: Array(2)
0: {_id: 1, name: "popps"}
1: {_id: 9, name: "sc"} 
 

正在检索板的我的主页组件:

import { Link } from 'react-router-dom'
import { HOME_PAGE_LOADED, CHECK_IF_BOARD } from '../constants/actiontypes'
import React, { Component } from 'react'
import agent from '../agent'
import { connect } from 'react-redux'

const mapStateToProps = state => ({
     ...state.boardList
})


const mapDispatchToProps = dispatch => ({
    onLoad: (payload) => {
        dispatch({ type: HOME_PAGE_LOADED, payload })
    },
    check: (payload) => {
        dispatch({ type: CHECK_IF_BOARD, payload })
    }
})


export default connect(mapStateToProps, mapDispatchToProps)(Home)

在我的 Home 组件中,this.props.boards 的类型是一个对象,但是,redux 状态显示它是一个数组!!

【问题讨论】:

    标签: reactjs api redux react-redux


    【解决方案1】:

    使用扩展运算符:

    switch (action.type) {
            case HOME_PAGE_LOADED:
                const boards = action.payload.boards || []
                return ({...state, boardsList: {boards,
                boardCount:boards.length}})     
            default:
                return state
        }
    

    【讨论】:

      【解决方案2】:

      问题在于您的减速器,因为您的状态是嵌套的。将reducer改成:

      switch (action.type) {
              case HOME_PAGE_LOADED:
                  const boards = action.payload.boards || []
                  return Object.assign({}, state, {boardsList: {boards, 
                  boardCount:boards.length}})            
              default:
                  return state
          }
      

      问候

      【讨论】:

        猜你喜欢
        • 2018-09-18
        • 2018-06-04
        • 1970-01-01
        • 2016-11-24
        • 1970-01-01
        • 2021-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多