import React,{useEffect, useState} from 'react';
import MaterialTable from 'material-table';
import axios from 'axios';
// function for adding the
export default function MaterialTableDemo() {
const [state, setState] = React.useState({
columns: [
{ title: 'Id', field: 'Id' },
{ title: 'Todo', field: 'Todo' },
{ title: 'Description', field: 'Description', type: 'numeric' },
],
data: [],
});
// get the state here
useEffect(()=>{
axios.get('http://localhost:4000/todos').then((res)=>{
{console.log(res.data)}
state.data = res.data
{console.log(state)}
})
})
return (
<MaterialTable
title="Todo Example"
columns={state.columns}
data={state.data}
/>
);
}
1){console.log(state)}在useEffect挂钩中打印以下数据
{columns: Array(3), data: Array(7)}
columns: (3) [{…}, {…}, {…}]
data: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
__proto__: Object
2)在我的材料表中未显示任何数据,我为什么不呢?但我可以看到我的列名
3)我支持的api正在运行,我正在获得响应
4)我不知道,是什么原因导致错误,无论是异步性质还是钩子用法
5)我的页面不断向api发送请求,以使其如何像componentdid mount()一样工作
答案 0 :(得分:1)
field
道具中的 columns
属性(键)应与data
道具中的属性(键)匹配。例如:
import React, { useEffect, useState } from "react";
import MaterialTable from "material-table";
export default function App() {
const [state, setState] = React.useState({
columns: [
{ title: "Name", field: "name" },
{ title: "Surname", field: "surname" }
],
data: [{ name: "Zain", surname: "Ul Abideen" }]
});
return (
<MaterialTable
title="Todo Example"
columns={state.columns}
data={state.data}
/>
);
}
提示:
正确设置状态的方法是:
useEffect(()=>{
axios.get('http://localhost:4000/todos').then((res)=>{
{console.log(res.data)}
setState({
...state,
data: {...state.data, res.data}
})
{console.log(state)}
})
}, []) // Empty array brackets means you want only one time your component to do the things mentioned in `useEffect`, Brief [guide][2].
state.data = res.data
创建数据的浅表副本,而不是深表副本。这是article,可以进一步了解它。
答案 1 :(得分:0)
尝试
useEffect(()=>{
axios.get('http://localhost:4000/todos').then((res)=>{
{console.log(res.data)}
setState({
...state,
data: res.data,
});
{console.log(state)}
})
})