我想得到一个值的列表,只要它的值通过钩子setState函数改变了,我就会更新,但是我得到了一个错误,我不知道为什么...我得到的.map不是函数TypeError
下面是我的代码,我还有一个codesandbox链接:https://codesandbox.io/s/fervent-satoshi-zjbpg?file=/src/Incomes.js:23-1551
import axios from "axios";
import { useState, useEffect } from "react";
const fetchInvestment = async () => {
const res = await axios.get(
"https://6r3yk.sse.codesandbox.io/api/investments/60b2696de8be014bac79a2a1"
);
return res.data.invest.incomes;
};
export default function Incomes() {
const [incomes, setIncomes] = useState([]);
const [date, setDate] = useState(undefined);
const [value, setValue] = useState(undefined);
useEffect(() => {
const getInvestments = async () => {
const res = await fetchInvestment();
setIncomes(res);
};
if (incomes.length === 0) {
getInvestments();
}
console.log(incomes);
}, [incomes]);
return (
<div>
<h1>Hello CodeSandbox</h1>
<input
id="monthEl"
type="month"
value={date}
onChange={(e) => {
setDate(e.target.value);
}}
/>
<input
id="monthEl"
type="number"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<button
onClick={() => {
const income = {};
income[date] = Number(value);
setIncomes(incomes.push(income));
setTimeout(() => {
console.log(incomes);
}, 2000);
}}
>
Save
</button>
<ul>
{incomes.map((income) => (
<li key={Object.keys(income)}>
{Object.keys(income)}: {Object.values(income)}
</li>
))}
</ul>
</div>
);
}发布于 2021-06-02 05:36:27
替换此行:
setIncomes(incomes.push(income));有了这个
setIncomes([...incomes, income]);.push方法返回数组的长度,而不是实际的数组。您可以使用展开运算符来展开当前数组,然后将新项添加到数组的末尾。
这样做也应该是可行的:
incomes.push(incomes)
setIncomes(incomes)发布于 2021-06-02 05:38:08
可能是因为从API返回的数据不是数组,所以您会得到这个错误。从您的代码判断,我猜您期望的是一个键/值映射,在JS中它是一个对象。您也许能够使用Object.keys(incomes).map(...),但由于不知道具体的响应格式,我不能肯定。
你的代码还有另外两个问题:
首先,你不能push到incomes,因为它是一个React状态数组。相反,您需要使用setIncomes回调...
setIncomes([...incomes, income])此外,您使用Object.keys和Object.values的方式是不正确的。同样,如果不知道响应格式的细节,就不能说正确的方式是什么。
https://stackoverflow.com/questions/67796146
复制相似问题