【问题标题】:Load data in a function with .map使用 .map 在函数中加载数据
【发布时间】:2021-05-31 10:58:08
【问题描述】:

我有以下功能不工作:

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>

我错过了什么? 提前谢谢!

【问题讨论】:

  • 如果你把const posts = useSelector((state) =&gt; state.postReducer)放在useEffect之后?
  • 我试过了,还是不行,谢谢你的帮助!

标签: reactjs mongodb redux reducers dispatch


【解决方案1】:

您不能调用.map,因为posts 不是数组。你的 reducer 的初始状态是一个对象。

const initialState = {}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 2013-09-11
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多