我需要在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中检查该对象吗?
尽管您可以在JSX中运行JavaScript表达式,但在JSX中使用过多的JavaScript逻辑来使其膨胀却不是一个好方法。对于类组件,应在componentDidMount()
生命周期挂钩中处理上述功能,对于功能组件,应在useEffect
挂钩中处理上述逻辑。
componentDidUpdate() {
fetch('/api/v1/attributes/'+scopedFormData.single_attributes_label)
.then(res => res.json())
.then(data => {
console.log(data);
// do the rest here
});
}
您可能想做这样的事情:
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>;
可能是因为异步函数返回的promise将被解析为value而不是value itselsf。