React useState() 数组未在 useEffect() 内更新

问题描述 投票:0回答:1
import { useState, useEffect } from "react";
import 'react-tabulator/lib/styles.css';
import { ReactTabulator } from 'react-tabulator'

export default function Project() {
    const [projects, setProjects] = useState([]);

    
    const [isLoading, setLoading] = useState(true);
    const projectListUri = '/api/projects';
    // const apiPath = process.env.REACT_SERVER_HOST + projectListUri;
    useEffect(() => {
        fetch("http://localhost:8000/api/projects")
            .then((response) => response.json())
            .then((data) => {
                console.log(data); // line 16
                setProjects(data);
                console.log(projects); //line 18
                setLoading(false);
            }).catch((error) => {
                console.log(error.message);
                setLoading(false);
            });
    }, []);

    return (
        <div>
            {isLoading ? (
                <p>Loading...</p>
            ) : (
                <ReactTabulator
                    data={projects}
                    autoColumns={true}
                    layout={"fitColumns"}
                />
            )}
        </div>
    );



}

上面是我在应用程序中运行的代码。我正在从后端服务器获取数据。获取数据一切顺利。我可以看到第 16 行正确记录的数据。但第 18 行始终显示一个空数组。因此 Tabulator 库给出

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'slice').
isLoading 常量正确更新。

我已经尝试过

setProjects(...data); setProjects([data]); setProjects(...projects, ...data);
都不起作用。

reactjs fetch tabulator
1个回答
0
投票

设置后您无法立即访问您的状态。您的错误似乎是数据不是来自您的 API,请尝试将其设为异步函数,如下所示:

const [projects, setProjects] = useState([]);
console.log(projects);

const [isLoading, setLoading] = useState(true);
const projectListUri = '/api/projects';
   
const getProjects = async () => { 
const result = await fetch("http://localhost:8000/api/projects")
    .then((response) => response.json())
    .then((data) => {
        setProjects(data);
        setLoading(false);
         }).catch((error) => {
            console.log(error.message);
            setLoading(false);
         });
 }
© www.soinside.com 2019 - 2024. All rights reserved.