作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要在 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/
我是一名优秀的程序员,十分优秀!