首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在API请求之外打印值

如何在API请求之外打印值
EN

Stack Overflow用户
提问于 2020-10-15 16:18:54
回答 1查看 49关注 0票数 0

我需要在API请求中为我的变量设置值,然后在函数外部请求中使用它。

代码语言:javascript
运行
复制
import React from 'react'

export default async (req, res) => {
  if (req.method === 'GET') {
    try {
      const imageToBase64 = require('image-to-base64')
      
      const [a,setA] = React.useState('')

      imageToBase64('url') // Path to the image
      .then(
          (response) => {
             setA(response)
          }
      )
      .catch(
          (error) => {
              console.log(error); // Logs an error if there was one
          }
      )
           console.log('a')
    } catch (error) {
      console.error(error)
    }
  }
}

问题是我编辑的文件只使用导出默认值,它没有包装在扩展React.Component的类中,也没有使用渲染函数。如何将响应值分配给变量?

EN

回答 1

Stack Overflow用户

发布于 2020-10-15 16:24:33

代码语言:javascript
运行
复制
import React, {useEffect, useState} from 'react'

export default const ApiCall = (req, res) => {
  const [a,setA] = useState('')
  useEffect(() => {
   if (req.method === 'GET') {
    try {
      const imageToBase64 = require('image-to-base64')
      imageToBase64('url') // Path to the image
      .then(
          (response) => {
             setA(response)
          }
      )
      .catch(
          (error) => {
              console.log(error); // Logs an error if there was one
          }
      )
           console.log('a')
    } catch (error) {
      console.error(error)
    }
  }
}, [req])
  
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64367522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档