基于React在博客应用程序中更新和删除帖子:第4部分

Wordpress7个月前发布 SUYEONE
745 0 0

In the previous part of this Series. you learned how to add and display blog posts in a React application. In this section of the React blog app tutorial, we’ll dive into implementing the functionality to update and delete blog posts. Let’s start by cloning the source code from the previous part:

1. Clone the repository: `git clone https://github.com/royagasthyan/ReactBlogApp-AddPost`
2. Navigate to the project directory and install dependencies: `cd ReactBlogApp-AddPost` and `npm install`
3. Start the Node.js server; the app will run at `http://localhost:7777/index.htML#/`

### Creating Update and Delete Views

Modify the blog post list to display Data in a table format with update and delete icons. In the `ShowPost` component’s `render` method, replace the existing `div` with a `table`, as shown:

“`jsx

{this.state.posts.map((post, index) => (

).bind(this))}

# Title Subject
{index + 1} {post.title} {post.subject}

“`

Save these changes and restart the server. Access the browser at `http://localhost:7777/home#/` to view the blog post list in a tabular format.

To implement the update feature, attach a click event to the eDiT icon:

“`jsx
this.updatePost(post._id)} className=”glyPhi-con glyphicon-pencil”>
“`

In the `ShowPost` component, create an `updatePost` method:

“`jsx
updatePost(id) {
hashHistory.push(`/addpost/${id}`);
}
“`

Update the router to include an optional `id` parameter in the `AddPost` page:

“`jsx

“`

In the `AddPost` component, create a `getPostWithId` method to fetch the blog post detAIls using the ID:

“`jsx
getPostWithId() {
const id = this.props.params.id;
axios.post(“/getPostWithId”, { id }).then((response) => {
if (response) {
this.setState({ title: response.data.title });
this.setState({ subject: response.data.subject });
}
}).catch((error) => {
console.log(‘Error is’, error);
});
}
“`

Display the state variables’ values in the title and subject text boxes:

“`jsx

暂无评论...
☺一键登录开启个人书签等功能!