【问题标题】:React - API call with Axios, how to bind an onClick event with an API CallReact - 使用 Axios 进行 API 调用,如何将 onClick 事件与 API 调用绑定
【发布时间】:2020-12-15 15:03:54
【问题描述】:

我有一个组件,就是句柄输入组件

import React, {useState} from 'react';
import FacebookApiCall from './Api'

export default function FacebookInterest () {
    const [interest, setInterest] = useState('');

    function HandleChange(event) {
        setInterest(event.target.value);
    }

    return (
    <div className="maincontainer">
      <input className="searchbar" type="text" placeholder="Type an interest ..." value={interest} onChange={HandleChange}/>
      <button onClick={() => FacebookApiCall(interest)} className="searchbutton">Search</button>
    </div>
    );
}

当用户点击时,我想通过 FacebookApiCall 调用 API

    import React, {useEffect} from 'react'
    import axios from 'axios'


export default function FacebookApiCall(props) {
    
    const url = `https://graph.facebook.com/search?type=adinterest&q=${props}&limit=10000&locale=en_US&access_token=EA`
    
     useEffect(() => {
         axios.get(url)
            .then(res => {
                console.log(url);
                console.log(res);
                
                //console.log(res.data.data[62].audience_size);
                //console.log(res.data.data[62].name);
                //console.log(res.data.data[62].description);
                //console.log(res.data.data[62].path);
            })
        });
        return (null);
}

react 返回的错误是:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用中拥有多个 React 副本

所以我不能在我的 Facebook 函数中使用钩子,我知道现在我如何在不使用 useEffect 的情况下进行 api 调用,如果无论如何我都必须使用 useEffect,我应该怎么做?我不得不承认我在这里迷路了。

非常感谢大家

【问题讨论】:

    标签: reactjs axios react-hooks


    【解决方案1】:

    所以看起来你违反了钩子规则之一:

    仅从 React 函数调用 Hooks

    在您的 FacebookApiCall 中,您正在从非反应函数调用 useEffect 挂钩。

    执行此操作的正确方法是从组件中的函数进行 api 调用。

    import React, { useState, useEffect } from 'react';
    
    function FacebookInterest () {
       const url = `https://graph.facebook.com/search?type=adinterest&q=${props}&limit=10000&locale=en_US&access_token=EA`
       const [interest, setInterest] = useState(null);
       const [response, setResponse] = useState(null);
    
       useEffect(() => {
          // If you want do do some other action after
          // the response is set do it here. This useEffect will only fire
          // when response changes.
       }, [response]); // Makes the useEffect dependent on response.
    
       function callYourAPI() {
          axios.get(url).then(res => {
             // Handle Your response here.
             // Likely you may want to set some state
             setResponse(res);
          });
       };
    
       function HandleChange(event) {
          setInterest(event.target.value);
       };
    
       return (
          <div className="maincontainer">
             <input
               className="searchbar"
               type="text"
               placeholder="Type an interest ..."
               value={interest}
               onChange={HandleChange}
             />
             <button
               onClick={() => callYourAPI(interest)}   
               className="searchbutton"
               // You may want to disable your button until interest is set
               disabled={interest === null}
             >
               Search
             </button>
          </div>
       );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2018-02-08
      • 2021-11-10
      • 2023-04-10
      相关资源
      最近更新 更多