Reactjs Axios承诺值始终呈现';未定义';
在子组件的Reactjs Axios承诺值始终呈现';未定义';,reactjs,axios,undefined,Reactjs,Axios,Undefined,在子组件的componentDiMount函数中,我使用外部函数(getResults)填充状态值。此函数使用axios调用外部API 这是我的密码: componentDidMount() { const cluster = '...'; const index= '...'; const field= '...'; const paragraphs = uuids.map(uuid => { // Get the result
componentDiMount
函数中,我使用外部函数(getResults
)填充状态值。此函数使用axios调用外部API
这是我的密码:
componentDidMount() {
const cluster = '...';
const index= '...';
const field= '...';
const paragraphs = uuids.map(uuid => {
// Get the results.
getResults(cluster, index, field, uuid, 'source')
.then(results => {
// Get value with console.log OK.
console.log(results);
// Return a undefined value...
return results;
})
.catch(error => {
console.error(error);
});
});
在阅读了很多很多帖子后,我发现我的问题似乎是axios生成结果的延迟。为了解决我的问题,我测试了许多解决方案,但都没有成功:在“渲染”部分检查渲染值
我如何解决这个问题?我是在componentDiMount
函数中修改元素,还是直接在外部getResults
函数中修改元素
感谢您的帮助。通常情况下,在axios请求中,数据会出现在结果中。数据 另外,由于您不返回
.map
中的任何内容,因此它将只是未定义的数组
您需要返回.map
componentDidMount() {
const cluster = '...';
const index= '...';
const field= '...';
const paragraphs = uuids.map(uuid => {
// Get the results.
// ADDED RETURN INSIDE .map
return getResults(cluster, index, field, uuid, 'source')
.then(results => {
// Get value with console.log OK.
console.log(results);
// Return a undefined value...
return results;
})
.catch(error => {
console.error(error);
});
});
如果你想从段落
中获取数据,你需要使用承诺。所有的或异步
/等待它工作。这假设UUID中有一些东西-如果你在映射之前控制台.log()它,它会显示什么?是的,const UUID是一个具有多个值的数组。我正在创建常量“段落”来传递state.data中的数组。也许我应该修改代码,将setState包含在map函数中。。。