如下代码所示,我请求了数据后,发现我几乎无法在 componentDidMount方法之外只用它所返回的数据。这令我很沮丧,请问有什么解决方案吗?
function componentDidMount()
{
//如果下面这句不加return,则下面arr显示undefined,加了则返回一个promise对象(如下两张图所示);
axios.get(http://10.15.58.125:8000/showProjects/
)
.then(res => {
return res.data.data;
});
}
let arr;
//想调用componentDidMount()来获取返回的数据进行后续的处理
//实际上返回的是一个promise对象
arr = componentDidMount();
你这种写法,是吧componentDidMount写成了函数?不太对吧。你把function去掉,然后可以用个state里的变量保存一下。至于undefined,应该是取错值了吧。你打印一下res看看是不是两层data