【问题标题】:Problem rendering fetched data with reactjs and firebase使用 reactjs 和 firebase 渲染获取的数据时出现问题
【发布时间】:2021-04-26 00:03:52
【问题描述】:

我正在尝试获取包含如下所示 JSON 数组的数据

[
   {
     "prof": "Jason Crank",
     "views": "2",
     //etc etc
   }
]

我正在尝试将 JSON 对象转换为一个 JavaScript 数组,我可以映射和渲染适当数量的块,我正在使用 typescript,这是我的代码

const [notesArr, setNotesArr] = useState<notesInterface[]>([])

const fetchNotes = async (active) => {
    try{
        const response = await fetch("my server", {
            method:"GET",
            headers: {'Content-Type': 'application/json'}
        })
        .then(resp => JSON.parse(JSON.stringify(resp)))
        .then(result => setNotesArr(result))
        

        return(
            <div>
                {notesArr.map((notes) => <NoteThumb link={notes.link} title={notes.title} semester={notes.semester} prof={notes.prof} timestamp={notes.timestamp} likes={notes.likes} views={notes.views} pages={notes.pages} isBookmarked={notes.isBookmarked}/>)}
            </div>
        )

    }catch(error){
        console.log(error)
    }
}

我使用的界面是这样的

interface notesInterface {
    prof: string
    views: number
}

尝试此操作时,我收到一条错误消息,上面写着Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

如果有任何帮助,我将不胜感激,如有必要,我可以提供更多我的代码的 sn-ps

【问题讨论】:

  • 将您的return (...) 移出 fetchNotes 函数。你在哪里打电话给fetchNotes
  • @Phil 我在函数组件的返回中调用它
  • @Phil 它是反应函数组件中的一个函数
  • 你能发布你的&lt;NoteThumb /&gt;组件吗?
  • 为了获取数据,你应该使用useEffect钩子并在那里调用你的函数fetchNotes,并在你的函数中删除渲染,它必须在return语句中。

标签: javascript reactjs firebase


【解决方案1】:

总结一下你在上面的 cmets 中被告知的内容......

  1. 您的功能组件需要返回 JSX 节点,而不是您的 fetchNotes 函数
  2. 使用useEffect在组件挂载上执行fetchNotes
const Notes: React.FC = () => {
  const [notesArr, setNotesArr] = useState<notesInterface[]>([])

  useEffect(async () => {
    try {
      const response = await fetch("my server")
      if (!response.ok) {
        throw new Error(`${response.status}: ${await response.text()}`)
      }
      setNotesArr(await response.json())
    } catch (err) {
      console.error(err)
    }
  })
  
  return (
    <div>
      {notesArr.map(note => <NoteThumb {...note} />)}
    </div>
  )
}

我也清理了你的fetch() 电话; GET 是默认的方法GET 请求没有Content-type,因为没有请求正文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2021-04-29
    • 2020-12-27
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多