如何在JavaScript中存储fetch()执行后的值并更新state?
解决fetch异步更新state时返回Promise的问题
你直接把fetch返回的Promise赋值给了state.product,而fetch是异步操作——代码不会等待请求完成再往下执行,所以同步运行的console.log(state.product)会先打印出处于等待状态的Promise对象。只有当请求完成后,then里的回调才会触发,这时候才能拿到正确的接口返回值。
正确写法1:在then回调内更新state
把state的更新逻辑放到then的回调函数里,确保拿到数据后再赋值:
fetch("https://fakestoreapi.com/products/2") .then(res => res.json()) .then(json => { console.log(json); // 正确值 state.product = json; // 在此处更新state console.log(state.product); // 现在能获取正确值 });
正确写法2:用async/await简化异步代码
如果运行环境支持ES7+,可以用async/await让代码逻辑更接近同步写法:
async function fetchProduct() { const res = await fetch("https://fakestoreapi.com/products/2"); const json = await res.json(); state.product = json; console.log(state.product); // 正确值 } fetchProduct();
注意:async函数本身也会返回Promise,所以如果在同步代码里调用fetchProduct()后立刻打印state.product,仍可能拿不到值,需等待异步操作完成。
内容的提问来源于stack exchange,提问作者Gaganpreet Singh
相关产品推荐
相关产品推荐

