Javascript 反向渲染状态时删除状态中的对象

Javascript 反向渲染状态时删除状态中的对象,javascript,reactjs,Javascript,Reactjs,在为一个网站做评论时,我遇到了一个大问题。目前,我有一个删除按钮,它根据州的索引拼接州的评论。我需要向用户反向显示数组——因此,当用户做出多个注释时,最新的注释是ontop 问题是,如果我反转()映射的数组,则索引不会随之反转,因此单击项目1的“删除”将删除最后一个项目,反之亦然 const [userComments, setUserComments] = useState([]) const postComment = (event, userComment) => { if (

在为一个网站做评论时,我遇到了一个大问题。目前,我有一个删除按钮,它根据州的索引拼接州的评论。我需要向用户反向显示数组——因此,当用户做出多个注释时,最新的注释是ontop

问题是,如果我反转()映射的数组,则索引不会随之反转,因此单击项目1的“删除”将删除最后一个项目,反之亦然

const [userComments, setUserComments] = useState([])

const postComment = (event, userComment) => {
  if (event.key === 'Enter') {
    setUserComments(prevState => ([...prevState, {comment: userComment}]))
  }
}

const deleteComment = (e, i) => {
  const userCommentsArray = [...userComments]
  userCommentsArray.splice(i, 1)
  setUserComments(prevState => ([...prevState], userCommentsArray))
}

return (
  <input 
  placeholder="Add a public comment" 
  onKeyUp={event => postComment(event, event.currentTarget.value)}
  onClick={event => showCommentButtons()}
  />
  { userComments 
    ? userComments.map((item, i) => (
      <div className="button" onClick={e => deleteComment(e, i)}>Button</div>
      <p className="comment">{item.comment}</p>
    ))
    : null
  }
)
const[userComments,setUserComments]=useState([])
const postComment=(事件、用户注释)=>{
如果(event.key=='Enter'){
setUserComments(prevState=>([…prevState,{comment:userComment}]))
}
}
常量deleteComment=(e,i)=>{
const userCommentsArray=[…userComments]
userCommentsArray.splice(i,1)
setUserComments(prevState=>([…prevState],userCommentsArray))
}
返回(
postComment(event,event.currentTarget.value)}
onClick={event=>showcomentbuttons()}
/>
{userComments
?userComments.map((项目,i)=>(
deleteComment(e,i)}>按钮

{item.comment}

)) :null } )
在阵列上使用反向方法:

const deleteComment = (e, i) => {
  const userCommentsArray = [...userComments].reverse()
  userCommentsArray.splice(i, 1)
  setUserComments(prevState => ([...prevState], userCommentsArray.reverse()))
}

我明白了。使用“取消移动”将项目按相反顺序推送到状态

无需进行其他更改

  const postComment = (userComment) => {
    const userCommentNotBlank = !userComment.trim().length < 1
    if (userCommentNotBlank) {
      const newState = [...userComments]
      newState.unshift(userComment)
      setUserComments(prevState => ([...prevState], newState))
      resetAddComment()
    }
  }
const postComment=(userComment)=>{
const userCommentNotBlank=!userComment.trim()。长度<1
if(userCommentNotBlank){
const newState=[…userComments]
newState.unshift(userComment)
setUserComments(prevState=>([…prevState],newState))
resetAddComment()
}
}

这些评论不是有自己的身份吗?如果没有,首先构建
comments.map((comment,index)=>({…comment,index}))
然后将其反转。您的注释应该有一个与每个注释相关联的
id
,这将帮助您跟踪注释,并帮助您在选择性DOM更新中做出反应。使用数组索引来标识注释是一个非常糟糕的主意。@AkshitMehra想这样做,但无法理解。有什么方法可以为它们生成一个随机id,该id也可以通过函数从状态中查找和删除?@robrtc您可以使用
uuid
包来检查post comment函数。注释按正常顺序发送到状态,因此使用此建议会立即反转所有用户注释。需要弄清楚如何将注释推送到反向状态。在删除后设置状态之前,如何将注释反向。