我需要在API请求中为我的变量设置值,然后在函数外部请求中使用它。
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的类中,也没有使用渲染函数。如何将响应值分配给变量?
发布于 2020-10-15 16:24:33
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])
}
https://stackoverflow.com/questions/64367522
复制相似问题