我在尝试删除评论应用程序项目中的一个回复时遇到问题。我的回复的删除按钮的onClick函数会不断删除整个评论,而不仅仅是“一个”回复处于回复数组状态的迭代。它必须处理我如何引用我所拥有的答复数组的状态。由于状态,我不确定如何引用数组的状态。
我已经尝试将state引用为变量,然后将引用state数组。
//State for component
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
commentArray: [
{
message: "Hello",
showReply: false,
reply: [
{ replies: "Hi there." },
],
id: 1
}]
}
//Function to splice one reply
handleRemoveReply = (index) => {
let replyArray = this.state.commentArray.reply
this.setState({
reply: replyArray.splice(index, 1)
})
}
}
我希望只删除一个答复,而不是整个评论。使用我尝试过的方法,我只能删除看起来似乎完整的评论。一直说状态是不确定的,所以这是一个参考问题。
答案 0 :(得分:1)
据我所知,对于您的状态数据结构,您实际上并未与状态正确交互。您必须首先获得给定注释的replyArray,然后需要将状态设置回原始数据结构。还要注意的是,拼接在数组上执行拼接操作,但是返回删除的对象。因此,除非您想将状态设置为已删除的状态,否则要先对数组进行拼接,然后再将状态设置为新结果。
//Function to splice one reply
handleRemoveReply = (index) => {
let replyArray = this.state.commentArray.reply
this.setState({
reply: replyArray.splice(index, 1)
})
}
}
尝试一下:
// Also pass what comment index you are interacting with
handleRemoveReply = (commentIndex, index) => {
const commentArray = [...this.state.commentArray]
commentArray[commentIndex].reply.splice(index, 1)
this.setState({
commentArray
})
}
}
编辑:已更新为复制状态,而不是直接对其进行突变