【问题标题】:Is there a way to save [[Promise Result]] as a state variable in the 'index.js'page?有没有办法将 [[Promise Result]] 保存为“index.js”页面中的状态变量?
【发布时间】:2021-09-29 07:34:01
【问题描述】:

我试图从“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 状态的方法。

【问题讨论】:

  • 您无法直接访问该值。你在 Promise 上使用 await.then() 从 Promise 中获取值。这是获得价值的唯一两种方法。关于 promise 的事情是,你永远不知道值何时在 promise 中,所以你使用 .then()await 来获取值。如果价值已经存在,那么它们几乎会立即为您提供价值。如果该值尚不存在(承诺仍在等待中),他们会在该值存在时通知您。这就是 Promise 的工作方式。没有其他方法可以使用 Promise。
  • 将初始状态设为空数组,并在承诺完成时更新它。
  • 哦,我不知道在 promise 上使用“await”或“.then()”!我两个都用过!谢谢你的建议!

标签: reactjs async-await react-redux state es6-promise


【解决方案1】:

您可以先将 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()

【讨论】:

  • 感谢您的善意建议!正如您所说,我尝试逐行理解代码!但它不起作用,我在“try”代码中找不到我应该修复的位置,它返回 Array(25) 很好,但结果是“error”(返回“catch”块)我在哪里可以修改这段代码?你能帮帮我吗!
猜你喜欢
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多