Unable to update a list with react when its value is being changed using the hook useState function from React TypeError: map is not a function

Unable to update a list with react when its value is being changed using the hook useState function from React TypeError: map is not a function

我想在通过钩子 setState 函数更改其值时更新值列表,但是我收到一个错误,我不知道为什么...我收到一个 .map 不是函数类型错误

下面是我的代码,我还有一个codesandbox link: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>
  );
}

替换此行:

setIncomes(incomes.push(income));

有了这个

setIncomes([...incomes, income]);

.push方法returns数组的长度,不是实际的数组。您可以使用扩展运算符扩展当前数组,然后将新项目添加到它的末尾。

这样做也应该有效:

incomes.push(incomes)
setIncomes(incomes)

您收到该错误可能是因为从 API 返回的数据不是数组。从你的代码来看,我猜你期待一个 key/value 地图,它在 JS 中是一个对象。您可能可以使用Object.keys(incomes).map(...),但不知道具体的响应格式,我不能肯定。

您的代码还有 2 个问题:

首先,你不能 pushincomes 因为它是一个 React 状态数组。相反,您需要使用 setIncomes 回调...

setIncomes([...incomes, income])

此外,您使用 Object.keysObject.values 的方式不正确。同样,如果不知道您的响应格式的具体细节,就无法说出正确的方法。