React中useState异步问题

我想通过[dataSource,setDataSource]=useState(tableProps)的方式给dataSource赋值,然后在组件中作为数据源渲染,但是tableProps是通过发送ajax请求,从后端接口得到,所以当我给dataSource赋值时,tableProps还没有拿到,以至于表格渲染出之后没有数据,请问怎么解决呢

可以使用 async 和 await 关键字来实现异步函数。

const [dataSource, setDataSource] = useState(null);

async function getTableProps() {
  const response = await fetch('/api/table-props');
  const tableProps = await response.json();
  setDataSource(tableProps);
}

useEffect(() => {
  getTableProps();
}, []);


在这段代码中,我们通过使用 async 和 await 关键字创建了一个异步函数 getTableProps。在函数中,我们使用 fetch 函数来获取后端接口返回的数据,并使用 setDataSource 函数将数据设置为 dataSource 的值。

我们还使用了 useEffect hook 来在组件挂载时调用 getTableProps 函数。这样,我们就可以在组件挂载后等待后端接口返回数据,并在获取到数据后将其设置为表格的数据源。

没必要初始化时使用异步数据,徒增不必要的麻烦。初始化请求数据赋值就可以了