我是个新手,我正在尝试使用UseEffect钩子向后端发出一个http请求,以获取一些数据,然后将其显示在materialTable中,但是状态数据不会更新,直到第二个渲染,导致一个空的dataTable。这是我的代码:
export default function MembersList() {
const [state, setState] = React.useState({
columns: [
{ title: "First Name", field: "firstName" },
{ title: "Last Name", field: "lastName" }
],
data: []
});
useEffect(() => {
async function fetchData() {
const result = await axios("http://localhost:3300/members");
return result;
}
fetchData().then(result => setState({ data: result.data }));
console.log("useEffect hook is called");
}, []);
console.log("state.data", state.data);
return state.data.length === 0 ? (
"no data to display"
) : (
<MaterialTable
title="Members List"
columns={state.columns}
data={state.data}
editable={{
onRowAdd: newData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...state.data];
data.push(newData);
setState({ ...state, data });
}, 600);
}),
onRowUpdate: (newData, oldData) =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...state.data];
data[data.indexOf(oldData)] = newData;
setState({ ...state, data });
}, 600);
}),
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...state.data];
data.splice(data.indexOf(oldData), 1);
setState({ ...state, data });
}, 600);
})
}}
/>
);
}
我在做什么错了?
答案 0 :(得分:2)
React.useState()不会进行浅层合并,因为React.Component类中提供了setState方法
setState((prevState) => ({
...prevState,
data: result.data
}))