首页 > 解决方案 > 'void' 类型的参数不能分配给 'SetStateAction | 类型的参数 不明确的'

问题描述

我正在从事一个实践项目(TypeScript Project),并从端点获取数据。我正在正确获取数据,但是当我尝试nft使用setNftuseState 挂钩将其分配给我的状态时,它会抛出我并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
  }, [])

错误图像

获取数据图像

标签: reactjstypescriptapifetch

解决方案


问题

问题在于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))  
  }, [])

推荐阅读