reactjs - 在 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
解决方案
你可以这样做。
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")}>
推荐阅读
- python - random.randint 与变量 | 如何
- python - 使用 boto3 python api 终止 ECS 任务
- mysql - sql join 返回两个相同的值
- c# - 如何使用 EF 核心和 BulkExtensions 批量插入
- git - 这个分支是 X 提前提交
- api - DocuSign API 错误 (Invalid_Client) 阻止 OAuth2 令牌生成
- c++ - 试图传递一个 constexpr lambda 并使用它来显式指定返回类型
- vb.net - IE11 中的 VB .NET 第三方超长 URL
- azure-powershell - 无法在辅助角色上安装 Azure/AzureRM PowerShell 模块
- mysql - MySQL子查询用NULLIF截断结果