首页 > 解决方案 > 使用 .map 在函数中加载数据

问题描述

我有以下不工作的功能:

import React, {useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getPosts } from '../../actions/post.actions';


const BudgetChart = () => {

const [loadPost, setLoadPost] = useState(true)
const dispatch  = useDispatch()

const posts = useSelector((state) => state.postReducer)

    useEffect(() => {
        if(loadPost) {
            dispatch(getPosts())
            setLoadPost(false)
        }
    }, [loadPost])

const amounts = posts.map(post => post.amount);

const income = amounts
    .filter(post => post.nature === 'ca')
    .reduce((acc, post) => acc + post.amount, 0)

    console.log(amounts)
    console.log(income)


    return (
        <div>
            CA Total = {income}
        </div>
    )
}

export default BudgetChart

const amount = posts.map(post => post.amount) 不起作用。错误是“posts.map 不是函数”。

这是我的减速器中的内容:

import { GET_POSTS } from "../actions/post.actions";

const initialState = {}

export default function postReducer(state = initialState, action) {
    switch (action.type) {
        case GET_POSTS:
            return action.payload
        default: 
            return state
    }
}

到目前为止,它只是这样工作:

return (
      <div>
          <ul>
          {!isEmpty(posts[0]) && 
          <li>
             CA Total : {posts.filter(post => post.nature === 'ca')
                              .reduce((acc, post) => acc + post.amount, 0)
                              }
          </li>
            }
          </ul>

我错过了什么?先感谢您!

标签: reactjsmongodbreduxreducersdispatch

解决方案


你不能打电话.map,因为posts它不是一个数组。你的 reducer 的初始状态是一个对象。

const initialState = {}

如果它是一个数组,请将初始状态设为一个空数组[],并确保action.payloadofGET_POSTS是一个数组。


推荐阅读