javascript - TypeError:无法读取未定义的属性(读取“作者”)
问题描述
当我提交空白表格时,会发生上述错误。我提交的 API 将引发错误,因为它不应留空。我似乎无法理解这一点。如果这段代码写得不好,我深表歉意,但我猜这与呈现页面时未定义的状态之一有关。似乎“handleSubmit”的“catch”块正在将数据状态更改为未定义的状态。
import "./Homepage.css"
import React, { useState, useEffect, useRef } from "react"
import useFetch from "./useFetch"
import Axios from "axios"
export default function Homepage() {
const [body, setBody] = useState("")
const [sortedData, setSortedData] = useState("")
const [data, setData] = useState("")
const [errorFlash, setErrorFlash] = useState("")
const [successFlash, setSuccessFlash] = useState("")
const posts = useFetch("http://localhost:5000/api/data")
const firstRender = useRef(true)
useEffect(() => {
setData(posts) //initiates data on first render
})
useEffect(() => {
if (firstRender.current) {
firstRender.current = false // Will prevent function from running on first render
return
}
data.sort(function (a, b) {
return new Date(b.date) - new Date(a.date)
})
setSortedData(data)
}, [data]) // Dependency set to "data" state, should run after data is fetched
const handleSubmit = (e) => {
e.preventDefault()
Axios.post("http://localhost:5000/api/react-create-post", { text: body }, { withCredentials: true })
.then((res) => {
console.log(res.data)
setSuccessFlash(res.data.msg) // res.data.msg is "Successfully created post"
setSortedData((prevArray) => [res.data.post, ...prevArray])
setBody("")
})
.catch((err) => {
setErrorFlash("Field cannot be left blank")
})
}
return (
<div>
<center>
<div className="create-container">
<div className="posts-title">Create Post</div>
<form id="theForm" onSubmit={(e) => handleSubmit(e)}>
<textarea onChange={(e) => setBody(e.target.value)} value={`${body}`} id="theInput" className="post-input" name="text" type="text"></textarea>
<button className="submit-btn">POST</button>
</form>
</div>
<div id="postsContainer" className="posts-container">
<div className="posts-title">Latest Posts</div>
{errorFlash ? <div className="error-msg">{errorFlash}</div> : console.log()}
{successFlash ? <div className="success-msg">{successFlash}</div> : console.log()}
<div id="postInput">
{sortedData &&
sortedData.map((item) => {
return (
<div className="post-container" key={item._id}>
<a className="a" href={`/user/${item.author}`}>
<h3 className="author">{item.author}</h3>
</a>
<div className="date">{item.date.toLocaleString()}</div>
<div className="options-cont">
<button id="optionsBtn" className="options-btn">
<i className="fas fa-ellipsis-v"></i>
</button>
<button data-author={`${item.author}`} data-id={`${item._id}`} data-text={`${item.body}`} id="editBtn" className="edit inside-btn invisible">
Edit
</button>
<button data-author={`${item.author}`} data-id={`${item._id}`} id="deleteBtn" className="delete inside-btn invisible">
Delete
</button>
<br></br>
<button className="invisible-two">Delete</button>
</div>
<p className="body-text">{item.body}</p>
</div>
)
})}
</div>
</div>
</center>
</div>
)
}
//useFetch hook in useFetch.js file
import { useState, useEffect } from "react"
export default function useFetch(url) {
const [data, setData] = useState("")
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((info) => {
setData(info)
})
}, [url])
return data
}
///API Code
exports.apiPostCreate = function (req, res) {
let post = new Post(req.body.text, req.verifiedUser.item.username)
post
.create()
.then((item) => {
res.status(201).send({ post: item, msg: "Post successfully created" })
})
.catch((err) => {
res.status(201).send({ err }) //This is what gets sent back in the "catch" block of the client-side
})
}
基本上,当“handleSubmit”的“catch”块执行时会发生错误。其他一切似乎都正常。
解决方案
我发现了错误。在我的 API 中尝试发布失败后,我原来的代码如下:
res.status(201).send({ err })
这意味着“then”仍在执行 Axios 请求。从那以后,我将状态码更改为 500,现在一切正常。
推荐阅读
- ios - 如何在 SwiftUI 中从 HealthKit API 导入 stepCount
- rest - 如何通过 GitLab API 在特定组中创建项目?
- postgresql - 如何使 postgres(光标?)从特定行开始
- javascript - React无法读取excel文件
- oop - 我无法通过调用默认构造函数来创建 ClassMirror 的新实例
- javascript - Next.js 是否在以下配置中为每个帖子生成一个页面?
- csh - csh 的撇号处理不清楚
- algorithm - 来自裸机的 scheme48 中的 GCD 功能
- python - 在 localhost 或命令行上运行包括 HTML 在内的 python 文件的问题
- c# - 按父母和孩子以及孩子的父母的顺序列表