我如何在FormDataConsumer中使用异步Javascript函数,例如fetch

问题描述 投票:2回答:3

我需要在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中检查该对象吗?

javascript node.js reactjs asynchronous react-admin
3个回答
1
投票

尽管您可以在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
    });
}

0
投票

您可能想做这样的事情:

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>;

0
投票

可能是因为异步函数返回的promise将被解析为value而不是value itselsf。

© www.soinside.com 2019 - 2024. All rights reserved.