测试代码大概是这样的
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 实现吗?如果可以,代码要如何调整呢?
![]() | 1 duduaba 2021-03-05 10:59:24 +08:00 没用过这个,我感觉你是对 hooks 不理解。 OperationButtons 里 refetch 是异步的,异步调用然后才根据数据变化执行 render,那这时候你 取 error 和 data 肯定获取不到 hooks 更新的信息对吧? 你看看可以加个 useEffect 监听 data 搞定。 |
![]() | 2 feng32 OP |
![]() | 3 feng32 OP okOk => onOk |
4 privatezcoding 2021-03-05 11:26:57 +08:00 http 请求是异步的,可以尝试使用 async await 转同步,再获取 data 和 error |
5 zhuweiyou 2021-03-05 11:32:41 +08:00 ![]() useXX 的结果是一个 reactive 值, 你需要 useEffect(() => { TODO: }, [监听的值]) |
![]() | 6 duduaba 2021-03-05 14:02:45 +08:00 @feng32 函数式组件只是 react 的一种组件写法返回的是 jsx 语法的 dom,onOk 是完全的 js 纯函数,肯定有区别的啊 |
![]() | 7 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); } } ``` |
8 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 了() |