类型错误:无法读取未定义的属性(读取"作者")



提交空白表单时出现上述错误。我提交的API将抛出一个错误,因为它不应该留空。我似乎不明白这是怎么回事。如果这段代码写得很糟糕,我很抱歉,但我猜这与页面呈现时未定义的状态之一有关。这似乎是"捕获"。handlessubmit "正在将数据状态更改为未定义的东西。

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
})
}

基本上错误发生在"catch"handlessubmit "执行。

我发现了错误。在我的API中,在一个不成功的post尝试之后,我原来有这个代码:

res.status(201).send({ err })

这意味着"then"仍在执行Axios的请求。我把状态码改成了500,现在一切正常了。

相关内容

  • 没有找到相关文章

最新更新