reactjs - 使用 .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>
我错过了什么?先感谢您!
解决方案
你不能打电话.map
,因为posts
它不是一个数组。你的 reducer 的初始状态是一个对象。
const initialState = {}
如果它是一个数组,请将初始状态设为一个空数组[]
,并确保action.payload
ofGET_POSTS
是一个数组。
推荐阅读
- android - Flutter LockTask
- javascript - 一种在悬停而不是单击时触发子菜单的方法?
- python - 将 pandas 数据框中的值添加到列表中
- google-app-maker - Google 应用制作工具表查询 _notContains 不起作用
- minecraft-forge - 项目 forge 1.12.2 (intellij idea) 加载模型/纹理的问题
- c# - 如何检测烛台图中的异常值
- c# - List.Find 在 C# 代码中返回错误
- ios - 为什么我的视图控制器没有填满整个屏幕?
- c++ - 算法设计:在 C++ 中用边界数字表示 2D 网格的最佳方式?
- r - 如何用 IQR 内的值替换多个变量和个体的异常值