【问题标题】:promise returned from axios.get [duplicate]从 axios.get 返回的承诺 [重复]
【发布时间】:2021-07-22 17:14:15
【问题描述】:

这是一个发出 Axios.get() 请求的函数:

 const mentorName = (value) => {
    try {
      const res = Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return
      }
    } catch (error) {
      console.log(error)
    }
  }

以下是控制台的输出:

Please Click here to see console output

现在,我想访问 res.data.data.consultant 但是当我尝试这样做时。它说 res.data 无效。这可能是因为它包含在一个承诺中。请帮我告诉如何访问它???

编辑:

按照建议使用 async/await:

 const mentorName = async (value) => {
    try {
      const res = await Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return
      }
    } catch (error) {
      console.log(error)
    }
  } 

Async/await 给出以下错误: 对象作为 React 子级无效(找到:[object Promise])。

编辑 2:

mentorName 在 array.map((row, index)) 中使用。我很确定调用该函数没有任何问题。

<TableCell align="left">
   {mentorName(row.consultantID)}
</TableCell>

【问题讨论】:

  • 要使用 axios,你需要使用 aysnc/await。尝试将mentorName 转换为异步函数,然后等待Axios.get
  • 不!编写 async 和 await 后,程序给出错误“对象作为 React 子项无效(找到:[object Promise])”
  • @ParasBansal 我的建议不是答案。请编辑问题以显示您尝试过的内容。
  • 我编辑了这个问题。请再次查看。
  • 给出的错误与示例中的代码无关。您可能会将对象直接转储到反应组件中。

标签: javascript reactjs promise axios


【解决方案1】:

我已经发布了一个解决方案来解决您的问题。不过可以查看this的帖子更详细的了解解决方案。

 const mentorName = async (value) => {
    try {
      const res = await Axios.get(
        `${BASE_URL}/api/v1/consultations/${value}`
      )
      if (res.status !== 200 || res.data.status !== "success") {
        console.log(res)
        return 'N/A'
      }
      return res.data.name;
    } catch (error) {
      return 'N/A'
    }
  }

使用 React Hooks

​​​
class App extends Component {
  constructor() {
    super();
    this.state = { row: { consultantID: 123 } };
  }
  componentDidMount() {
      const consultantID = this.state.row;
      mentorName(consultantID).then((name) => {
        this.setState({
            ...this.state,
            row: { ...this.state.row, name }
        });
    });
  }
  render() {
    return (
        <TableCell align="left">
           {row.name}
        </TableCell>
    );
  }
}

反应 useState() 方法

docs

   const App = (props) => {
        const [row, setRow] = useState({ consultantID: 123, name: 'N/A' });
    
     mentorName(row.consultantID).then(name =>setRow({
        ...row,
        name,
    }))
    
    return (
       <TableCell align="left">
           {row.name}
        </TableCell>
    )
}

【讨论】:

  • “使用 React Hooks” 标题下方的示例没有使用 React Hooks?
  • 是的。那不是完整的代码。我已经放了文档的参考。
  • 不,我的意思是它不使用反应钩子...useState 是反应钩子
  • 我认为你不需要一个反应钩子来更新状态。在then() fn 我正在更新状态。检查这个codesandbox.io/s/hooks-rg1qd
猜你喜欢
  • 2020-03-24
  • 1970-01-01
  • 2015-11-04
  • 2016-10-20
  • 2018-06-03
  • 2015-02-13
  • 2019-04-21
  • 1970-01-01
  • 2020-08-26
相关资源
最近更新 更多