我需要在FormDataConsumer标记内使用提取,但似乎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>;