通过 API 调用加载反应 table

Loading react table through API call

我有 2 个组件,A 和 B。A 通过道具将 2 个数据点传递给 B,在 B 内部我使用这些道具进行 API 调用。但是,这会引发错误:“TypeError:data.forEach 不是函数”。一旦错误消息显示在控制台中,应该在反应 table 中填充的结果也会在几分钟后被记录下来。我无法理解我哪里出错了。感谢您的帮助!

const TableT = (props) => {
    const [data, setData] = useState([])
    async function fetchTableData(t, d){
        await Aios.get("http://localhost:4000/api?dataset="+d+"/table="+t).then((res) => {
            console.log(res.data)
            return res.data
        })
    }
    useEffect(() => {
        let d = fetchTableData(props.dataset, props.table)
        setData(d)
    }, [data])

    //Here comes the standard code of react table, rendered using the "data" state
}

我认为 table 在我们通过 API 调用获得数据之前就已呈现,因此出现错误(我可能是错的)。如果需要,很乐意澄清任何事情!

您对 async/await 的使用在这里有点不正统,坦率地说,没有必要。以下是我将如何更正您的代码:

const TableT = (props) => {
    const [data, setData] = useState([])
    const fetchTableData = (t, d) => {
        Aios.get("http://localhost:4000/api?dataset="+d+"/table="+t).then((res) => {
            console.log(res.data)
            setData(res.data);
        });
    }
    useEffect(() => {
        fetchTableData(props.dataset, props.table);
    }, [])

    //Here comes the standard code of react table, rendered using the "data" state
}

当然,这假定 props.dataset, props.table 已正确传递并且您的 axios 实际上调用了 returns 数据。

无需等待 axios 调用的响应,您可以在 then 中获取它并在那里设置状态变量。