有没有办法将 [[Promise Result]] 保存为“index.js”页面中的状态变量?

我试图从“index.js”文件中的异步调用中获取数组。

// index.js

const loadItem = async () => {
  const items = await axios.get("https://api.example.com")
    .then(res => {
      return res.data
    })
    .catch(() => {
      console.log('error')
    });
  console.log([items])       // Array(25)
  return [items]
};
loadItem()


//And want to put this result value to in initstate(to make reducer) as below.



const initState = loadItem();

function reducer(state=initState,action) {
  return state
}

但是,在App.js 页面的“console.log(props.state)”之后,我可以看到下面的结果

// App.js

Promise
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(25)

在这种情况下,我如何访问 [PromiseResult] 作为状态值

(我想将此 Array 值作为 initState 值 放在“index.js”页面中)

我希望使用这个 Array,但是我找不到访问这个 PromiseResult 状态的方法。

ning419 回答:有没有办法将 [[Promise Result]] 保存为“index.js”页面中的状态变量?

你可以先把 initState 作为一个空数组,然后当数据从 api 调用返回时分派一个动作来更新状态

// reducer.js

const initState = []

function reducer(state=initState,action) {
  switch(action.type){
      case "UPDATE_DATA": return action.data
      default: return state
  }

}


// index.js
const loadItem = async () => {
  try{
      const items = await axios.get("https://api.example.com")
      console.log([items])       // Array(25)
      dispatch({action: "UPDATE_DATA",data: items})
  } catch(e){
    console.log('error')
  }
};
loadItem()
本文链接:https://www.f2er.com/56888.html

大家都在问