gpt4 book ai didi

javascript - 我们可以在 Axios 中做一个 If 吗 - ReactJS

转载 作者:行者123 更新时间:2023-11-28 14:11:24 24 4
gpt4 key购买 nike

我写这篇文章是因为我想知道是否可以在 axios 中执行 if 。基本上我试图仅使用 axios 发送带有内容的变量。

我有一个全局代码,如下所示:

 async handleSubmit(event) {
this.setState({ loading: true });

setTimeout(() => {
this.setState({ loading: false });
}, 2000);

event.preventDefault();
const {
name_contact='', name_contact1='', endfr='', endfr_1='',
} = this.state;


const name = [name_contact, name_contact1].filter(v =>v).join(',');
const end = [name_contact, name_contact1].filter(v =>v).join(',');

await axios.post(
' MY_endpoint API',
{
name, end
})
}

例如,如果 name_contactname_contact1 为空,我将收到 name=""与我的 axios.post。但我试图删除 name 或 end 如果它们是空的,以便 axios.post 只发送有用的内容而不是完全空的变量。

所以我告诉自己,我可以在 axios 中执行 if 来检查变量的内容,如果有内容就发送它。

最佳答案

不显式检查每个字段的更通用方法

const payload = {name, end, /*other fields*/};

//filtering not empty fields
const result = Object
.keys(payload)
.filter(key => payload[key] !== '')
.reduce((result, key) => ({...result, [key]: payload[key]}), {});

// Or just use Lodash _.pickBy
const result = _.pickBy(payload, field => field !== '');

await axios.post('MY_endpoint API', result);

关于javascript - 我们可以在 Axios 中做一个 If 吗 - ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com