【问题标题】:TypeError: Cannot read property 'map' of undefined,, trying to read from mongodb类型错误:无法读取未定义的属性“地图”,试图从 mongodb 中读取
【发布时间】:2021-09-30 12:33:53
【问题描述】:

/// 我正在关注 youtube 上的一篇教程, https://www.youtube.com/watch?v=nUbNn0voiBI&t=88s 并遇到错误,

代理错误:无法将请求 /notes 从 localhost:3000 代理到 https://localhost:3001/。 请参阅https://nodejs.org/api/errors.html#errors_common_system_errors 了解更多信息(EPROTO)。


function Notes(){
    const [notes, setNotes] = useState([{
        name: '',
        email: '',
        phone: '',
        message: ''
    }])

    useEffect(() => {
        fetch("/notes").then(res => {
            if(res.ok) {
                return res.json()
            }
        }).then(jsonRes => setNotes(jsonRes));
    })

    return <div className="container">
        <h1>Notes page</h1>
        {notes.map(note => 
            <div>
                <h1>{note.name}</h1>
                <p>{note.email}</p>
                <p>{note.phone}</p>
                <p>{note.message}</p>
            </div>            
            )}
    </div>
}

export default Notes;```

【问题讨论】:

  • 可能是您从 API 调用获得的响应不是数组或未定义。因为, .map 将仅在数组上运行。你能检查一下你从 API 得到什么响应吗?

标签: reactjs mongodb get-request


【解决方案1】:

您应该尝试 console.log(jsonRes) 并确保您返回一个数组。 map 函数仅适用于数组:/ 注释的 useState 也毫无意义,只需将其设为 useState([])。如果你 console.log(jsonRes) 返回一个对象列表。您可以使用 setNotes(jsonRes).toArray() 应该可以。这一切都取决于你从 mongodb 返回什么

【讨论】:

    【解决方案2】:

    您可以在使用地图之前检查注释是否未定义,我将使用您的代码在下面做一个示例。

    function Notes(){
        const [notes, setNotes] = useState([{
            name: '',
            email: '',
            phone: '',
            message: ''
        }])
    
        useEffect(() => {
            fetch("/notes").then(res => {
                if(res.ok) {
                    return res.json()
                }
            }).then(jsonRes => setNotes(jsonRes));
        })
    
        return <div className="container">
            <h1>Notes page</h1>
            {notes !== undefined && notes.map(note => 
                <div>
                    <h1>{note.name}</h1>
                    <p>{note.email}</p>
                    <p>{note.phone}</p>
                    <p>{note.message}</p>
                </div>            
                )}
        </div>
    }
    
    export default Notes;
    

    这样你可以防止你的数组未定义导致你描述的这个错误。

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2023-01-03
      • 2014-09-02
      相关资源
      最近更新 更多