gpt4 book ai didi

javascript - 如何在 FormDataConsumer 中使用异步 javascript 函数(例如 fetch)

转载 作者:行者123 更新时间:2023-12-03 13:42:35 25 4
gpt4 key购买 nike

我需要在 FormDataConsumer 标记内使用 fetch,但 FormDataConsumer 似乎不支持异步函数。此代码对我不起作用:

<FormDataConsumer>
{
async ({ formData, scopedFormData, getSource, ...rest }) => {
return await fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
.then(res => res.json())
.then(data => {
console.log(JSON.stringify(data));
//return JSON.stringify(data);
resolve(JSON.stringify(data));
});
return JSON.stringify(scopedFormData);
}
}
</FormDataConsumer>

我还检查了这段代码,这个也不起作用:

async function getAttrItem(id) {
return await fetch(`/api/v1/attributes/${id}`).then(response => response.json())
}

...

<FormDataConsumer>
{
async ({ formData, scopedFormData, getSource, ...rest }) => {
return await JSON.stringify(getAttrItem(scopedFormData.single_attributes_label));
}
}
</FormDataConsumer>

但是当我使用这个时,它可以在控制台中运行:

<FormDataConsumer>
{
({ formData, scopedFormData, getSource, ...rest }) => {
fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
.then(res => res.json())
.then(data => {
console.log(JSON.stringify(data));
//return JSON.stringify(data);
resolve(JSON.stringify(data));
});
return JSON.stringify(scopedFormData);
}
}
</FormDataConsumer>

我应该使用这个 FormDataConsumer 来填充对象,然后在另一个 FormDataConsumer 中检查该对象吗?

最佳答案

你可能想做这样的事情:

const MyComponent = props => {
const [data, setData] = useState();

useEffect(() => {
fetch("/api/v1/attributes/" + props.attribute)
.then(res => res.json())
.then(data => {
setData(data);
});
}, [props.attribute]);

if (!data) {
return <someloadingindicator />;
}

// now you got your data. you can now return some component that uses the data here
};


// now in your component where using the FormDataConsumer
<FormDataConsumer>
{({ formData, scopedFormData, getSource, ...rest }) => {
return <MyComponent attribute={scopedFormData.single_attributes_label} />;
}}
</FormDataConsumer>;

关于javascript - 如何在 FormDataConsumer 中使用异步 javascript 函数(例如 fetch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59528291/

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