javascript - 将对象添加到状态的属性中,该属性是 React 中的数组
问题描述
这是我第一次尝试做一个 React 项目。我对它很陌生,所以我只是根据不同的 youtube 频道来制作它,我相信你会觉得它很乱,所以我很抱歉。
我正在做一个博客项目,我想为每篇文章制作一个评论组件。我在网上获取了一些对象用作帖子,但由于没有评论属性,我尝试使用 useEffect 添加它。但是,使用 useState 提交时,我无法添加到评论中。我一定是用错了。我会在控制台中检查帖子对象,但评论数组是空的。
应用程序.js
const App = () => {
const [posts, setPosts] = useState([]);
const [isLoading, setIsLoading] = useState(true)
const [showForm, setShowForm] = useState(false)
const [comments, setComments] = useState([])
//fetch
useEffect( () => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(posts => {
setIsLoading(false)
posts = posts.map(post => {
post.comment = comments;
return post
})
setPosts(posts.slice(0, 1))
})
}, [])
//add comment
const addComment = (e, {title}, id) => {
e.preventDefault()
console.log("Comment: ", title)
console.log("ID of post: ", id)
const addedComments = posts.map(post => {
if(post.id === id) {
setComments(
...comments,
{
id: uuid.v4,
title: {title}
}
)
}
})
}
CommentForm.js
const CommentForm = ({id, addComment}) => {
const commentItems = <Comments />
const [commentData, setCommentData] = useState({
title: "",
})
const {title} = commentData
const onChangeHandler = (e) => {
setCommentData({
...commentData,
[e.target.name] : e.target.value
})
}
return (
<div>
<form onSubmit={ (e) => addComment(e, commentData, id) }>
{JSON.stringify(commentData)}
<div className="form-group">
<label htmlFor="title">Add comment:</label>
<input
type="text"
name="title"
value={title}
onChange={ (e) => onChangeHandler(e)}
/>
<button>Submit</button>
{ commentItems }
</div>
</form>
</div>
)
}
控制台输出
App.js:64 Comment: Test comment
App.js:67 ID of post: 1
App.js:26
[{…}]
0:
userId: 1
id: 1
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
body: "quia et suscipit↵suscipit recusandae consequuntur expedita et cum↵reprehenderit molestiae ut ut quas totam↵nostrum rerum est autem sunt rem eveniet architecto"
comment: Array(0)
length: 0
__proto__: Array(0)
__proto__: Object
length: 1
解决方案
您破坏数组的方式似乎不正确
if (post.id === id) {
setComments([
...comments,
{
id: uuid.v4,
title: { title },
},
]);
}
推荐阅读
- reactjs - 如何在获取方法 React 中使用日期从服务器下载数据?
- nest-device-access - Google Nest 摄像头访问权限
- php - 使用按钮单击另一个 vue 组件或 html 按钮单击在不同页面中获取 vue 组件
- kubernetes - Kubernetes 列出所有未运行的容器
- lua - Lua:在两个字符串之间查找字符串
- javascript - MUI Tab-组件属性到 Tab 渲染但抛出异常
- java - SQL 语句中的错误:NoClassDefFoundError: com/macasaet/fernet/Validator
- javascript - 使用 JavaScript 在栏外单击时如何关闭侧边栏
- perl - 在 Solaris 11 中安装 DBI Perl 模块时出现问题
- audio - Alexa是如何编程唱歌的?