我使用
useMemo
来防止我的组件在每次状态更改时渲染。另外,我正在调用 CommonService().getLegalNamesById
,这只是一个异步 axios get 调用。但是,当我的 getLegalName
函数在 fetchResults
内被调用时,直到 fetchResults
完成之后才会被调用,因此 console.log("LegalName is: ", getLegalName(context[i].legalName[0]));
对于 getLegalName(context[i].legalName[0])
返回未定义,并且 console.log('testing order');
仅在 fetchResults
完成后打印,因此有我遇到一些执行顺序问题,我不确定为什么?
let panels = {documentSource: {summary: 'Document Source', content: new Set()},
legalName: {summary: 'Legal Name', content: new Set()},};
const AccordionFilter = () => {
const [context] = useContext(Context);
const getLegalName = (id) => {
CommonService()
.getLegalNamesById([id])
.then((response) => {
console.log('testing order');
const legal = response.data.results[0];
return legal.name + ' - ' + legal.id;
})
.catch((error) => {
console.log(error);
});
};
const fetchResults = () => {
for(let i = 0; i < context.length; i++) {
console.log("LegalName is: ", getLegalName(context[i].legalName[0]));
panels.documentSource.content.add(context[i].documentSource[0]);
panels.legalName.content.add(getLegalName(context[i].legalName[0]));
}
return panels;
};
const callBackFetchResults = useMemo(() => fetchResults(), [context]);
return (
<Accordion
panels={['documentSource', 'documentStatus', 'jpmcLegalEntityName', 'productName', 'documentTitle']}
renderPanel={({ value, getPanelProps }) => {
let panel = callBackFetchResults[value];
let panelArr = Array.from(panel.content);
return (
<Checkbox label={item} key={item} />
);
}
/>
);
/>
</div>
)};
axios 库向 REST 端点发出异步 HTTP 请求。 因此,在for循环中,函数getLegalName被调用,并且被跳过,并且不等待其响应,因此,将未定义的值视为其值。另外,您在 getLegalName 函数中执行了一个 Promise,而如果您打算在 getLegalName 中返回一个值,那么最好使用 async 和 wait 。
要解决此问题,请在.then中的面板中执行添加操作,确保axios响应已准备好,然后就可以使用它了。