0

我是新手,我正在尝试使用 UseEffect 挂钩向我的后端发出 http 请求以获取一些数据,然后将其显示在 materialTable 中,但是状态中的数据直到第二次渲染才会更新导致一个空的数据表。这是我的代码:

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);
          })
      }}
    />
  );
}

我究竟做错了什么 ?

4

1 回答 1

2

React.useState() 不像 React.Component 类中可用的 setState 方法那样进行浅合并

setState((prevState) => ({
 ...prevState,
 data: result.data
}))
于 2019-08-14T20:07:35.903 回答