首页 > 解决方案 > 在 react onClick 上激活 2 个不同的调用

问题描述

我的反应组件面临下一个场景:

我有 2 个按钮,它们的作用几乎相同,只是它们从不同的地方获取数据。

数据是从 axios 服务类上的 2 个不同函数中获取的,但是当从服务器返回时,应该执行相同的代码(在 then 和 catch 方法上)。

我怎样才能使只有获取将是一个单独的调用,但其余代码将是相同的?

axios 文件:

import axios from 'axios';

const ACCOUNT_API_BASE_URL = "http://localhost:8080/app";

class MyAxiosService {

    getAccount1(accountNumber) {
        
        return axios.post(ACCOUNT_API_BASE_URL + 'accounts', accountNumber);
    }

    getAccount2(accountNumber) {
        
        return axios.post(ACCOUNT_API_BASE_URL + 'findSecondWayAccount', accountNumber);
    }
}
export default new MyAxiosService()

零件:

import AccountService from '../services/AccountService'
import './web.css'
import Dropdown from 'react-dropdown'
import 'react-dropdown/style.css'
import React, { Component, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux';
import { useAlert } from "react-alert";
import MyAxiosService from '../services/MyAxiosService';

const Example = (props) => {
    

    const onClick1 = (event) => {
        event.preventDefault();
        MyAxiosService.getAccount1(1111).then(res => {
            //common logic for both calls
        }).catch(error => {
           //common error handling for both calls
        });
    };

    const onClick2 = (event) => {
        event.preventDefault();
        MyAxiosService.getAccount2(1111).then(res => {
            //common logic for both calls
        }).catch(error => {
           //common error handling for both calls
        });
    };

    return (
        <form >
            <div>
               
                    <div class="float">
                        <input id='accountNumber' pattern="\d{4}" maxlength="8" name='accountNumber' for="accountNumber" required='required' placeholder="מספר חשבון" value={findAccountCriteria.accountNumber} onChange={onInputChange} />
                    </div>

                    <div class="float">
                        <input type="submit" value="find1" class="ui-button" id="a1" onClick={onClick1} />
                    </div>

                    <div class="float">
                        <input type="submit" value="find2" class="ui-button" id="a2" onClick={onClick2} />
                    </div>
             </div>
                <br />
        </form>
    );
};

export default Example

标签: reactjs

解决方案


你可以这样做。

 const onClickCommon = (event, accountType) => {
        event.preventDefault();
        MyAxiosService[accountType](1111).then(res => {
            //common logic for both calls
        }).catch(error => {
           //common error handling for both calls
        });
    };
    
    
 <Button onClick={e => this.onClickCommon(e, "getAccount1")}>


推荐阅读