gpt4 book ai didi

javascript - react .js : Why delete button is not working?

转载 作者:行者123 更新时间:2023-12-04 01:32:06 24 4
gpt4 key购买 nike

我正在开发一个博客首页,我想通过简单的 setState 命令按下删除按钮来删除特定的帖子。我的 Blog.js 在下面:

import React from "react";
const BlogBody = props => {
return props.postData.map(post => {
const { title, author, content } = post;
return (
<React.Fragment key={post}>
<h2>{title}</h2>
<h5>
<i>{author}</i>
</h5>
<h3>{content}</h3>
<br />
<button onClick={()=>props.removePosts(post)}>Delete</button>
<hr />
</React.Fragment>
);
});
};

const Blog=(props)=>{
const {postData,removePosts}=props;
return(
<div>
<BlogBody postData={postData} removePosts={removePosts}/>
</div>
)
}

export default Blog;

App.js 代码如下:

import React,{Component} from 'react';
import Blog from './Blog'
import Createpost from './Createpost'


class App extends Component {
state={
user:'ali',
posts:[
{
title:'First',
author:'Written by Ali',
content:'first Post',
},
{
title:'Second',
author:'Written by Ali',
content:'Second Post',
},
{
title:'third',
author:'Written by Ali',
content:'third Post',
},
]
};
removePosts=index=>{
const{posts}=this.state

this.setState({
posts:posts.filter((post,i)=>{
return i!==index
}),
})
}
render(){
const {posts}=this.state
return (
<div style={{padding:8}} className="container">
<Createpost/>
<hr/>
<Blog postData={posts} removePosts={this.removePosts}/>
</div>
);
}

}

export default App ;

Createpost.js 如下:

import React, {Component} from 'react'
class Createpost extends Component {

render() {
return (
<form onSubmit={e=>e.preventDefault()}>
<div>
<label htmlFor="create-title">Title:</label>
<input type="text" name="create-title" id="create-title"/>
</div>
<textarea/>
<input type="submit" value="Create"/>
</form>
);
}
}

export default Createpost;

在执行 npm start 后没有错误显示,页面显示我现在想要的方式。但问题是当我按下删除按钮时,它不起作用,这意味着没有扣除任何帖子行。我不知道出了什么问题。请帮我解决这个问题。我最近才开始......所以我还有很多东西要学......如果你进一步解释它也会对我的理解有很大帮助。

提前致谢

最佳答案

问题出在 removePost 函数上因为您要传递整个帖子对象

<button onClick={()=>props.removePosts(post)}>Delete</button>

但是当你检查的时候你是在检查索引

return i!==index

**试试这个:**

   return props.postData.map((post, index) => {
const { title, author, content } = post;
return (
<React.Fragment key={post}>
<h2>{title}</h2>
<h5>
<i>{author}</i>
</h5>
<h3>{content}</h3>
<br />
<button onClick={()=>props.removePosts(index)}>Delete</button>
<hr />
</React.Fragment>
);
});

索引作为参数传递给函数

关于javascript - react .js : Why delete button is not working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60739828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com