状态不是设置

State is not Setting

我正在尝试存储我的后端的结果,这是一个库存列表,从我的后端发送,由 Microsoft .Net 6 Web API。

但我不明白为什么,当我尝试“设置”我的 inventory_state 的数组响应时 React 不保存它。

我在想我做错了 axios 服务吗?

这里:

SetInventory_state({
  ...inventory_state,
  inventories: response.data,
});

Axios 服务

// frontend\src\services\http-server.js
import axios from "axios";

const http = axios.create({
  baseURL: "http://192.168.1.10:1010/api/",
  headers: {
    "Content-type": "application/json",
  },
});
export default http;

DataServiceInventory

// frontend\src\services\Data\DataServiceInventory.js
import http from "../http-server";

class DataServiceInventory {
  AllList() {
    return http.get("/inventory/list/");
  }
}
export default new DataServiceInventory();

页面列表

// frontend\src\pages\PageInventoryIndex.js

const PageInventoryIndex = function () {
  const [inventory_state, SetInventory_state] = useState({
    inventories: null,
    error: null,
    loading: true,
  });
  const { error, loading, inventories } = inventory_state;

  async function getData() {
    try {
      await DataServiceInventory.AllList().then((response) => {
        console.log(response);
        SetInventory_state({
          ...inventory_state,
          inventories: response.data,
        });
      });
    } catch (err) {
      SetInventory_state({
        ...inventory_state,
        error: err.message,
      });
    } finally {
      SetInventory_state({
        ...inventory_state,
        loading: false,
      });
    }
  }

  useEffect(function () {
    getData();
  }, []);
  

  return (
    <>
      <Console stateName={inventory_state} />
      <Content MaxWidth="800px">
        <ContentHead>
          <IconTitle icon="fluent:clipboard-task-list-rtl-24-regular" />
          <h1>Lista de inventarios</h1>
        </ContentHead>

        <ContentBody>
          {loading && <div>Cargando...</div>}
          {error && (
            <div>{`Hay un problema al obtener los datos - ${error}`}</div>
          )}

          {inventories ? (
            <table id="customers">
              <thead>
                <tr>
                  <th>N#</th>
                  <th>Nombre del Inventario</th>
                  <th>Ubicación</th>
                  <th>Estado</th>
                  <th>Acción</th>
                </tr>
              </thead>
              <tbody>
                {inventories.map((item, index) => (
                  <tr key={index}>
                    <td>{item.inventory_id}</td>
                    <td>{item.name}</td>
                    <td>{item.location}</td>
                    {item.status ? (
                      <td>
                        <span className="badge bg-success">
                          Abierto
                        </span>
                      </td>
                    ) : (
                      <td>
                        <span className="badge bg-secondary">
                          Cerrado
                        </span>
                      </td>
                    )}

                    <td>
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/editar/`}
                      >
                        Ver
                      </Link>
                      |
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/editar/`}
                      >
                        Editar
                      </Link>
                      |
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/cerrar/`}
                      >
                        Cerrar
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : null}
        </ContentBody>
      </Content>
    </>
  );
};
export default PageInventoryIndex;

据我所知,您的 finally 块进行了第二次 SetInventory_state 调用,据我所知,它“覆盖”了第一个将所有正确值放入状态的调用。 在 finally 块中,使用了 ...inventory_state,它仍然是 API 响应中第一次 SetInventory_state 调用之前的旧值。