无法将来自服务器的响应保存到数组 React 状态

Unable to save to array React state from the response from the server

我试图将我的 response.data 保存到我的 React 数组状态,但它从未存储正确的数组。但是当我做一个临时数组时它起作用了。

const [allstudentlist, setAllStudentlist] = useState([]);

await Axios.post(currentUrl, params).then((res) => {
  // if res.data[0][]
  // if res data is there then;
  if (res.data["error"]) {
    alert(res.data["error"]);
  } else {
    // alert("Register Successful");
    // console.log(res.data[0]);
    console.log(res.data);

    // Works
    let temp = res.data;
    setAllStudentlist(...temp);

    // Works
    console.log(temp);

    // Returns an empty array
    console.log(allstudentlist);
  }
});

响应数据

Response data

我也尝试用假的 API 进行测试,但在 React 中设置数组似乎存在问题。

我也尝试使用 codeSandbox 以及假的 API 进行测试,但它不起作用。

import "./styles.css";
import React, { Component, useState, useEffect } from "react";

import Axios from "axios";
export default function App() {
  const [array2, setArray] = useState([]);

  function handleClick() {
    Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then(
      function (response) {
        console.log(response.data);
        setArray(response.data);
        console.log(array2);
      }
    );
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={handleClick}></button>
    </div>
  );
}

我该如何解决?

您无法在设置状态后立即看到更新的值,因为它是一个异步函数。您设置值的方式很好。移动控制台日志;

handleClick

之外
  function handleClick() {
    Axios.get("https://finalspaceapi.com/api/v0/character/?limit=2").then(
      function (response) {
        console.log(response.data);
        setArray(response.data);
      }
    );
  }

  console.log(array2);

将其保存在具有依赖性的 useEffect

  useEffect(() => {
    console.log(array2);
  }, [array2]);