将创建博客帖子,并且可以选择删除帖子。为此,我正在使用钩子。
应用程序.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;
创建post.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;
博客.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 start 后没有显示错误。但在浏览器中,TypeError: props.postData.map is not a function显示在 Blog.js
有人可以帮我吗?我被困在这里似乎永远。
我最近开始使用 reactjs,昨天开始做钩子。所以请帮忙。