无法获取react中具有useState和axios的数组[已关闭]

knsnq2tg  于 2022-11-23  发布在  iOS
关注(0)|答案(3)|浏览(135)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
13天前关闭。
这篇文章5天前被编辑并提交审查。
Improve this question
我有这样的数据库

[
  {
    "ymd": "2019-01-02",
    "dailyRevenue": 3464
  },
  {
    "ymd": "2019-01-03",
    "dailyRevenue": 3051
  },
  {
    "ymd": "2019-01-04",
    "dailyRevenue": 3495
  },
  {
    "ymd": "2019-01-05",
    "dailyRevenue": 4770
  },
  {
    "ymd": "2019-01-06",
    "dailyRevenue": 4907
  },
  {
    "ymd": "2019-01-07",
    "dailyRevenue": 2880
  },
]

这是我的密码

export default function Dashboard() {
    const API_URL = 'http://localhost:8000/api/';
    const reLabel = ['2019-03-12', '2019-09-24'],       reData = [432,345];
    const [revenueHistoryLabel, setRevenueHistoryLabel] = useState([]);
    const [revenueHistoryData, setRevenueHistoryData] = useState([]);

    useEffect(() => {
        axios.get(API_URL + 'revenues').then((res) => {
            setRevenueHistoryLabel(
                ...revenueHistoryLabel,
                res.data.map((element) => element.ymd),
            );
            setRevenueHistoryData(
                ...revenueHistoryData,
                res.data.map((element) => element.dailyRevenue),
            );
        });
    }, []);

我竭力想:

  • 检索ymd,然后将其作为数组放入revenueHistoryLabel,如['2019 -03- 12','2019-09- 24']
  • 检索dailyRevenue,然后将其作为数组放入revenueHistoryData,如[432,345]

但是在我调用了setRevenueHistoryLabel()和setRevenueHistoryData()之后,RevenueHistoryLabel和RevenueHistoryData仍然是空数组。

xdyibdwo

xdyibdwo1#

你能试试这个吗?

setRevenueHistoryLabel([
  ...revenuHistoryLabel,
  ...res.data.map((element) => element.ymd),
]);

setRevenueHistoryData([
  ...revenuHistoryData,
  ...res.data.map((element) => element.dailyRevenue),
]);

spread expressionsetState中的用法似乎是错误的。

7fyelxc5

7fyelxc52#

axios.get("")将您的链接放在这里,尽管将它放在另一个变量中
有时这种类型的错误发生,尝试让我知道。

t2a7ltrp

t2a7ltrp3#

export default function Dashboard() {
    const API_URL = 'http://localhost:8000/api/';
    const reLabel = ['2019-03-12', '2019-09-24'],       reData = [432,345];
    const [revenueHistoryLabel, setRevenueHistoryLabel] = useState([]);
    const [revenueHistoryData, setRevenueHistoryData] = useState([]);

    useEffect(() => {
        axios.get(API_URL + 'revenues').then((res) => {
            setRevenueHistoryLabel([
                ...revenueHistoryLabel,
                ...res.data.map((element) => element.ymd),
            ]);
            setRevenueHistoryData([
                ...revenueHistoryData,
                ...res.data.map((element) => element.dailyRevenue),
            ]);
        });
    }, []);

这是ans.console.log现在显示阵列。谢谢大家

相关问题