Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在onclick之后响应调用API_Reactjs_Typescript - Fatal编程技术网

Reactjs 在onclick之后响应调用API

Reactjs 在onclick之后响应调用API,reactjs,typescript,Reactjs,Typescript,在我的React应用程序中,我有一个按钮,单击该按钮,我正在调用一个函数以发出API请求,但是我看到Uncaught(In promise)ErrorError 我想知道我是否以正确的方式做了我现在做的事情 我以前在页面加载时使用了useffect来调用API,但不知道如何在单击按钮时执行此操作 因此,在渲染中,我有: <Fab onClick={approveIt}>Go</Fab> 任何帮助都将不胜感激 谢谢类似于try,catch语句,您必须在axios.post

在我的React应用程序中,我有一个按钮,单击该按钮,我正在调用一个函数以发出API请求,但是我看到
Uncaught(In promise)Error
Error

我想知道我是否以正确的方式做了我现在做的事情

我以前在页面加载时使用了
useffect
来调用API,但不知道如何在单击按钮时执行此操作

因此,在渲染中,我有:

<Fab onClick={approveIt}>Go</Fab>
任何帮助都将不胜感激


谢谢

类似于
try,catch
语句,您必须在
axios.post
调用中添加一个
.catch
,以防出现错误,以便处理它。你可以这样做:

axios.post(api, {}).then(response => {
      // Simplified - lets just get the response
      console.log(response.status)

      // And set some state
      setSuccess(true);
   })
   .catch(err => {
      console.log(err);
      setSuccess(false);
   });

try,catch
语句类似,为了处理错误,必须在
axios.post
调用中添加
.catch
。你可以这样做:

axios.post(api, {}).then(response => {
      // Simplified - lets just get the response
      console.log(response.status)

      // And set some state
      setSuccess(true);
   })
   .catch(err => {
      console.log(err);
      setSuccess(false);
   });

axios调用中可能有错误,您无法捕获它。您可以通过以下方式进行修复:

  axios.post(api, {})
    .then(response => {
      // Simplified - lets just get the response
      console.log(response.status)

      // And set some state
      setSuccess(true);
    })
    .catch((error) => { console.log(error); })

axios调用中可能有错误,您无法捕获它。您可以通过以下方式进行修复:

  axios.post(api, {})
    .then(response => {
      // Simplified - lets just get the response
      console.log(response.status)

      // And set some state
      setSuccess(true);
    })
    .catch((error) => { console.log(error); })

你做得基本上是对的。只是不确定是什么错误。您可以在承诺检查的结尾添加一个
.catch(err){console.log(err)}
。@hackape的想法是正确的,但这是无效的syntaxCool,所以我不需要一些嵌套的
useffect
(从我读到的内容来看是不允许的)或其他异步/wait/promisebusiness@userMod2不,那没必要,您只需确保为可能发生的错误添加一个
catch
处理程序就可以了。我想知道我是否遗漏了一些更基本的东西。谢谢,你做得很对。只是不确定是什么错误。您可以在承诺检查的结尾添加一个
.catch(err){console.log(err)}
。@hackape的想法是正确的,但这是无效的syntaxCool,所以我不需要一些嵌套的
useffect
(从我读到的内容来看是不允许的)或其他异步/wait/promisebusiness@userMod2不,那没必要,您只需确保为可能发生的错误添加一个
catch
处理程序就可以了。我想知道我是否遗漏了一些更基本的东西。谢谢