reactjs - 'void' 类型的参数不能分配给 'SetStateAction | 类型的参数 不明确的'
问题描述
我正在从事一个实践项目(TypeScript Project),并从端点获取数据。我正在正确获取数据,但是当我尝试nft
使用setNft
useState 挂钩将其分配给我的状态时,它会抛出我并useEffect
在最后出错setNft(data)
界面
interface Attributes {
type: string
value: string
}
interface Anu {
name: string
description: string
file: string
tokenstring: string
contentType: string
hathorLink: string
attributes: Attributes[]
}
代码
const [nft, setNft] = useState<Anu>()
useEffect(() => {
fetch("http://51.15.56.157:3000/anu/5000")
.then((res) => res.json())
.then((result) => console.log(result))
.then((data) => setNft(data)) <=== getting error here
}, [])
解决方案
问题
问题在于then
链接和arrow function
。
then() 方法返回一个 Promise。它最多需要两个参数:Promise 成功和失败情况的回调函数。
解决方案
通过删除第二个then
或在周围添加大括号来修复错误console.log
const [nft, setNft] = useState<Anu>()
useEffect(() => {
fetch("http://51.15.56.157:3000/anu/5000")
.then((res) => res.json())
.then((data) => setNft(data))
}, [])
或者,
const [nft, setNft] = useState<Anu>()
useEffect(() => {
fetch("http://51.15.56.157:3000/anu/5000")
.then((res) => res.json())
.then((result) => {
console.log(result)
return result; // ----> this return result will use as data in the next then !!
})
.then((data) => setNft(data))
}, [])
注意:请注意我在上述代码段中的评论。
解释:
以这种方式使用箭头函数(result) => console.log(result)
意味着:
function sample (result) {
return console.log(result)
}
在then
链接中,回调函数将返回您可能在下一个 then
使用但您返回aconsole.log
而不是您的data的东西。
所以你的代码看起来像这样,这显然是错误的并导致错误:
useEffect(() => {
fetch("http://51.15.56.157:3000/anu/5000")
.then((res) => res.json())
.then((console.log(result)) => setNft(data))
}, [])
推荐阅读
- entity-framework-core - 在单个请求中重用 DbContext?
- java - 如何调用 Drools excel 决策表函数
- python - 如何使用文本文件作为模板?
- visual-studio - 以编程方式在 Visual Studio 的配置管理器中为项目勾选“构建”
- c - 将常规彩色图像转换为模糊版本
- node.js - 布局未显示单独的路线文件
- javascript - 制作自适应 iframe,然后在单击按钮时允许全屏显示
- hadoop - 无法为 hadoop (win7) 启动 namenode
- python-3.x - 需要帮助大学一年级的家庭作业问题涉及循环
- c++ - 静态库中的多重定义