【问题标题】:How to append data to a component with useAsync hook?如何使用 useAsync 挂钩将数据附加到组件?
【发布时间】:2019-07-29 15:57:09
【问题描述】:

我正在使用 react-async 从 api 获取数据,如下所示:

import {useAsync} from 'react-async'

const getOrders = () => ...

const MyComponent = () => {
  const { data, error, isLoading } = useAsync({ promiseFn: getOrders })
  if (isLoading) return "Loading..."
  if (error) return `Oopsi`
  if (data)
    return (
      <div>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
    )
  return null
}

现在,我如何更新data(附加下一个回复)? 应该是这样的:

import {useAsync} from 'react-async'

const getOrders = (page) => ...

const MyComponent = () => {
  const [page, setPage] = React.useState(1);
  const { data, error, isLoading } = useAsync({ promiseFn: getOrders, page: page })

  if (isLoading) return "Loading..."
  if (error) return `Oopsi`
  if (data)
    return (
      <div>
        <pre>{JSON.stringify(data, null, 2)}</pre>
        <button onClick={() => {
                setPage(page + 1);
                getOrders()
                }>Get more orders</button>
      </div>
    )
  return null
}

【问题讨论】:

    标签: javascript reactjs react-async


    【解决方案1】:

    这目前没有内置到 React Async 中。唯一的方法是保留您自己的数据记录(使用单独的 useState)并在 React Async 的 onResolve 处理程序中更新它。

    我在这里为您设置了一个示例:https://codesandbox.io/s/react-async-pagination-og13b

    跟踪此功能请求已经存在问题:https://github.com/async-library/react-async/issues/103

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2017-04-04
      • 2020-10-25
      相关资源
      最近更新 更多