javascript - 刷新(重新调用)API 的 react 按钮

标签 javascript reactjs api

我有一个 API,每次我调用 API 时它都会给我一个随机位置,我希望按钮只是重新调用 API。

我尝试使用箭头函数和普通函数,但出现不同的错误;我的一般想法是用一个函数包装获取方法,然后调用此函数两次,第一次调用在我呈现组件之前调用,第二次调用此按钮。

这些是我的尝试:

(注意:我的错误函数是handleOnClick)

 state = {
   isLoading: true,
   shop: null, 
   error: null
 };

 componentDidMount() {
   // fix CORB and CORS issues by using proxy
   var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
     targetUrl ='https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g%20et_param=value';

     function handleOnClick() {
       fetch(proxyUrl + targetUrl)
     .then(res => res.json())
     .then(shop => {
       console.table(shop); // create table in console 
       this.setState({ 
         shop ,
         isLoading:false,
       });
     })
     .catch(e => {
       console.log(e);
     });    
   }

   handleOnClick();
 }


   showLocation = () => {
   var location = `${this.state.shop.lat}%2C%20${this.state.shop.lon}`;
  var gmapurl =`https://maps.google.com/maps?q=${location}&t=&z=17&ie=UTF8&iwloc=&output=embed`;
  return gmapurl;
};



 render() {

   const { isLoading, shop, error } = this.state; //no need to write this.state every time



   let gmapurl ;  //create variable that we will store the new location from the API 

   return (  


     <React.Fragment>
          <Navigation />

     <div> 
     {/* // Display a message if we faced an error */}
     {error ? <p>{error.message}</p> : null} 
     {!isLoading ? ( //   check data if it ready 
     //and take lat and lon from api ,and place it in  embedded google map url
    gmapurl =`https://maps.google.com/maps?q=${this.state.shop.lat}%2C%20${this.state.shop.lon}&t=&z=17&ie=UTF8&iwloc=&output=embed`,

       shop ? (
         <div>

           <h1> {this.state.shop.name}</h1>
        {/* MAP */}  
        <div className="mapouter MapPage"><div className="gmap_canvas">
           <iframe width="768" height="500" id="gmap_canvas" src={gmapurl} 
           frameBorder="0" scrolling="false" marginHeight="0" marginWidth="0">
           </iframe>
           <h1>map veiw</h1></div> 
           </div>


           <button className="btn" onClick={() =>  {handleOnClick}}> <div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div>أقتراح آخر</button>

        </div> ) : ( '')
):(      // show loading icon if there is a delay in data
<div> <img src={loadingpic}></img>  </div>
 )
     }
     </div>
     </React.Fragment>
   );
 }
}

这是我得到的错误


  Line 82:  Expected an assignment or function call and instead saw an expression no-unused-expressions

  Line 82:  'handleOnClick' is not defined  no-undef

最佳答案

您的handleOnClick 是一个本地函数,只能从componentDidMount 内部调用。为了能够从类中的任何地方调用它,请使用方法。也许名称应该更能描述它实际执行的任务,例如加载商店:

 loadShop() {
   this.setState({ isLoading: true });

  fetch(proxyUrl + targetUrl)
    .then(res => res.json())
    .then(shop => {
      console.table(shop);
      this.setState({ 
         shop ,
         isLoading:false,
      });
     });
 }

然后你可以从类中的任何地方调用它作为this.loadShop(),例如

 <button onClick={() => this.loadShop()} >

关于javascript - 刷新(重新调用)API 的 react 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55823885/

相关文章:

javascript - 使用 TypeScript 在 React 组件之外调度 Redux Thunk 操作

javascript - 从 PHP 渲染 React 组件

reactjs - 在 React 中使用 ApolloClient 订阅 AppSync

javascript - 如何使用Javascript将API检索的数据存储在本地并等间隔更新数据?

javascript - 如何使用 Parse 和 Mandrill 发送电子邮件通知?

javascript - 抽屉不适用于 `mdl-layout--fixed-header` 类

javascript - 通过 React 路由器将 prop 传递给组件

javascript - jQuery 搜索切换

api - Excel-自定义函数,Contoso.ADD42 函数未出现在 Excel 中

javascript - Mocha 要求我读取 HTTP 请求正文