将创建博客文章,并可以选择删除该文章。要做到这一点,我正在使用钩子。
App.js:
import React, { useState } from 'react';
import Blog from './Blog';
import Createpost from './Createpost';
const App = () => {
const [posts, setPosts] = useState('');
const removePosts = (index) => {
setPosts(posts.filter((post) => post.index !== index));
};
return (
<div style={{ padding: 8 }} className="container">
<br />
<hr />
{<Createpost posts={posts} setPosts={setPosts} />}
<hr />
<Blog postData={posts} removePosts={removePosts} />
</div>
);
};
export default App;
Createpost.js:
import React, { useState } from 'react';
const Createpost = ({ user, posts, setPosts }) => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const handleTitle = (event) => {
setTitle(event.target.value);
};
const handleContent = (event) => {
setContent(event.target.value);
};
const handleCreate = (event) => {
const newPost = { title, content, author: user };
setPosts({ newPost, ...posts });
};
return (
<form
onSubmit={(e) => {
e.preventDefault();
handleCreate();
}}
>
<div>
author:<b>{user}</b>
</div>
<div>
<label htmlFor="create-title">Title:</label>
<input
tytpe="text"
value={title}
onChange={handleTitle}
name="create-
title"
id="create-title"
/>
</div>{' '}
<textarea value={content} onChange={handleContent} />
<input type="submit" value="Create" />
</form>
);
};
export default Createpost;
Blog.js:
import React, { useState } from 'react';
const BlogBody = (props) => {
const rows = props.postData.map((post, index) => {
const [title, author, content] = post;
return (
<React.Fragment key={index}>
<h2>{title}</h2>
<h5>
<i>{author}</i>
</h5>
<h3>{content}</h3>
<br />
<button onClick={() => props.removePosts(index)}>Delete</button>
<hr />
</React.Fragment>
);
});
return <div>{rows}</div>;
};
const Blog = () => {
const [postData, removePosts] = useState('');
return (
<div>
<BlogBody postData={postData} removePosts={removePosts} />
</div>
);
};
export default Blog;
执行npm启动后没有错误显示。但在浏览器中,TypeError:props.postData.map不是Blog.js 中显示的函数
有人能帮我吗?我被困在这里似乎是永远。
我最近开始做reactjs,昨天开始做hook。所以请帮忙。
您正在将postData
创建为字符串:
const [postData, removePosts] = useState('');
如果您希望它是一个数组,则应该更改初始值。
const [posts, setPosts] = useState([]);
// Add posts:
setPosts((prevPosts) => [...prevPosts, 'new post'])
Map函数只能用于数组。
在这里,您将postData的初始状态分配为字符串
即const [postData, removePosts] = useState('');
请将useState中的初始状态更改为阵列
即const [postData, removePosts] = useState([]);