【问题标题】:Update object in react with condition statement更新对象以响应条件语句
【发布时间】:2022-09-15 05:31:47
【问题描述】:

如果有评论的条件,我会更新状态?.length,我只想在有评论的情况下更新评论,一切正常,但我有一个问题。 我可以更轻松地完成这种情况吗?我的意思是没有映射2次。

 const changeStatus = (id, status,comment) => {
    axios
      .post(\"http://localhost:5000/changeStatus\", {
        id: id,
        status: status,
        comment: comment,
      })
      .then((res) => {
          comment?.length
            ? setStatus(
                status.map((val) => {
                  return val.id == id
                    ? {
                        ...val,
                        status: status,
                        comment: comment
                      }
                    : val;
                })
              ) : setStatus(
                status.map((val) => {
                  return val.id == id
                    ? {
                        ...val,
                        status: status,
                      }
                    : val;
                })
              );

    标签: reactjs dictionary axios


    【解决方案1】:

    我认为您可以只映射一次并将条件放入对象中

    .then((res) => {
      setStatus(status.map((val) => {
        if(val.id === id){
          return {
            ...val,
            status: status,
            comment: comment.length ? comment : null
          }
        }
        return val
      })
    }
                    
    

    【讨论】:

    • 谢谢,但是 val.comment 没有清除评论而不是 null
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多