请教 useAxios (React Hooks) 的一个使用问题

2021-03-05 10:47:00 +08:00
 feng32

测试代码大概是这样的

const OperationButtons = ({record,}) => {
  const [{ data, loading, error}, refetch] = useAxios('http://www.baidu.com', {'manual': true});
  return (
    <Actions>
      <LinkButton
        onClick={() => {
          Dialog.confirm({
            title: "Confirm",
            content: 'Do you want to send request?',
              onOk: () => {
                refetch();
                if (error) {
                  console.log(error);
                }
                else {
                  console.log(data);
                }
              }
          });
        }}
      >
        Request
      </LinkButton>
    </Actions>
  )
}

const TestTable = () => {
  const [{data, loading, error}, refetch] = useAxios('http://data.cdc.gov/data.json');
  return (
    <Table
      dataSource={data?.dataset}
      loading={loading}
      columns={[
        {
          title: 'title',
          dataIndex: 'title',
        },
        {
          title: 'identifier',
          dataIndex: 'identifier',
        },
        {
          title: 'operations',
          cell: (value, index, record) => (
            <OperationButtons record={record} />
          )
        }
      ]}
    />
  );
};

这里调用了一个公开数据集 ( http://data.cdc.gov/data.json) 来渲染一个表格 (TestTable),表格渲染是正常的。表格的第三列里有一个按钮,按下后会弹出一个确认对话框,点击 Ok 后,会发第二个请求。

现在我想做的,是判断第二个请求成功与否,分别弹出一个成功对话框和失败对话框。

因为这个文件是函数式组件,所以第二个请求也想使用 useAxios 来实现。现在如果打开浏览器的 CORS,第二个请求确实发出去了,但是现在判断逻辑有问题,始终输出 undefined

请问这种情况下,第二个请求可以使用 axios-hooks 实现吗?如果可以,代码要如何调整呢?

1818 次点击
所在节点    程序员
8 条回复
duduaba
2021-03-05 10:59:24 +08:00
没用过这个,我感觉你是对 hooks 不理解。
OperationButtons 里 refetch 是异步的,异步调用然后才根据数据变化执行 render,那这时候你 取 error 和 data 肯定获取不到 hooks 更新的信息对吧? 你看看可以加个 useEffect 监听 data 搞定。
feng32
2021-03-05 11:16:27 +08:00
@coderfuns 请教一下,TestTable 是一个函数 (函数式组件), okOk 也是个函数

它们两在概念上有什么区别吗
feng32
2021-03-05 11:16:52 +08:00
okOk => onOk
privatezcoding
2021-03-05 11:26:57 +08:00
http 请求是异步的,可以尝试使用 async await 转同步,再获取 data 和 error
zhuweiyou
2021-03-05 11:32:41 +08:00
useXX 的结果是一个 reactive 值, 你需要

useEffect(() => {
TODO:
}, [监听的值])
duduaba
2021-03-05 14:02:45 +08:00
@feng32 函数式组件只是 react 的一种组件写法返回的是 jsx 语法的 dom,onOk 是完全的 js 纯函数,肯定有区别的啊
tangdw
2021-03-05 17:57:38 +08:00
refetch() 是异步函数吗?是的话 onOK 改一下,onOK 只会在点击后执行一次,函数组件会在 state 发生变化后执行

```js
async () => {
await refetch();
if (error) {
console.log(error);
}
else {
console.log(data);
}
}
```
islxyqwe
2021-03-05 18:18:22 +08:00
onOk: () => {refetch().then(resp=>console.log(resp.data), error => console.log(error));}
或者
useEffect(()=>{
if (error) {
console.log(error);
}
else {
console.log(data);
}
},[data,error])
/**...*/
onOk: refetch
楼上就属于不懂 hooks 了()

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/758707

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX