【问题标题】:setstate after splice with react与反应拼接后的设置状态
【发布时间】:2019-06-25 11:27:55
【问题描述】:

我做了一个删除,使用 react 完美。问题是删除后我想将状态设置为新的 extraitMP3 以在删除后刷新并自动显示结果。这是删除的功能:

 showDeleteConfirmation(value, id,idJson,thisHandler) {
    confirm({
      title: 'Voulez vous supprimer cette audio ?',
      content: '',
      okText: 'Oui, je confirme',
      okType: 'danger',
      cancelText: 'Non',
      onOk() {
        deleteMp3Request(id);

        var {extraitMP3} = thisHandler.state;
        Object.keys(extraitMP3).map(ids => {
          return(
          Object.keys(extraitMP3[ids].TypeMp3List).splice(idJson, 1)  
                )
        })
        thisHandler.setState({extraitMP3: extraitMP3})

        console.log('extraitMP3',extraitMP3)
        NotificationManager.success("le fichier audio est supprimé avec succès !", "");
      },
      onCancel() {
      },
    });
  }

这是我正在映射的 JSON:

这也是我的归来

 return (
<div>
      {loader ? <CircularProgress className="gx-loader-400" /> : Object.keys(extraitMP3).map(ids => {
        return (
          <Card>

            <li key={ids}>
              <Card styleName="gx-card-list icon icon-data-display gx-mr-2 gx-text-blue gx-fs-xl">
                <div className="gx-media-body">
                  {extraitMP3[ids].Typenom}
                  &nbsp; 
                  {extraitMP3[ids].TypeIcon != null &&
                    displayIcon(extraitMP3[ids].TypeIcon)
                  } 
                </div>

                {Object.keys(extraitMP3[ids].TypeMp3List).map(idJson => {
                    return (
                      <div className="gx-main-content gx-mb-4">
                          <ContainerHeader match={this.props.match} />
                          <div className="gx-contact-item gx-dragndrop-item">

                            <DragHandle />

                            <div className="gx-col gx-job-title ">
                              {extraitMP3[ids].TypeMp3List[idJson].intitule}
                            </div>

                            {extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon !== '' &&
                              <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation1Nom}>
                               {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon)}
                              </Tooltip>
                            }

                            {extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon !== '' &&
                              <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation2Nom}>
                              {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon)}
                              </Tooltip>
                            }

                            {extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon !== '' &&
                              <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation3Nom}>
                              {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon)}
                              </Tooltip>
                            }

                            {extraitMP3[ids].TypeMp3List[idJson].langueIcon !== '' &&
                              <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                                <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].langueNom}>
                                  <i className={`flag flag-24 gx-mr-2 ${extraitMP3[ids].TypeMp3List[idJson].langueIcon}`} />
                                </Tooltip>
                              </div>
                            }

                            <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                              <Select
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Selection la choix de votre numéro de téléphone "
                                optionFilterProp="children"
                                onChange={handleChangeSelect}
                                defaultValue={selectOptions.get(extraitMP3[ids].TypeMp3List[idJson].visibilite)}
                                filterOption={(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                              >
                                  {[...selectOptions].map(([value, label]) => <Option value={value}> {label} </Option>)}
                              </Select>
                            </div>

                            <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                              <i className="icon icon-edit gx-fs-xl gx-text-gris" />
                            </div>

                            <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                            <span className="gx-pointer">
                               <i  className="icon icon-trash gx-pointer gx-text-danger gx-fs-xxl"
                               id={extraitMP3[ids].TypeMp3List[idJson].id}
                               onClick={e => this.showDeleteConfirmation(e.target.value, extraitMP3[ids].TypeMp3List[idJson].id,idJson,this)} />
                            </span>                         
                             </div>

                          </div>

                      </div>
                    )
                })}
                  <NotificationContainer/>

                <Button type="primary" htmlType="submit" labelCol={{ xs: 24, sm: 5 }} wrapperCol={{ xs: 24, sm: 12 }}>
                  Enregistrer
                </Button>
              </Card>
            </li>
          </Card>
        )
      }) }</div>
    )

任何帮助将不胜感激。

【问题讨论】:

  • 什么是idJsonextraitMP3 是什么? extraitMP3[ids].TypeMp3List 是什么?
  • 问题是你正在修改的数组没有保留在任何地方,它是Object.keys(extraitMP3[ids].TypeMp3List)创建的数组,除非你将它保存在某个地方,否则它是临时的。恐怕从上面的问题中根本不清楚您要对您的状态做出什么改变(即使在您发布了“JSON”之后),所以我无法发布一个答案来告诉您如何做到这一点。
  • 是的,我想要做的就是保留修改后的数组。如何保存它以在刷新新结果后立即将其置于 setstate 上
  • 请检查返回函数,它将为您澄清事情我正在使用 id 进行删除。我想要做的只是在删除时刷新页面以显示删除后的结果。
  • 我在 15 分钟前回答了这个问题。如果您对答案有任何疑问,请对答案发表评论(在仔细阅读之后)。 :-)

标签: javascript reactjs react-native object


【解决方案1】:

问题是你正在修改的数组没有保留在任何地方,它是Object.keys(extraitMP3[ids].TypeMp3List)创建的数组,除非你将它保存在某个地方,否则它是临时的。

如果目标是从extraitMP3[ids] 中删除名称在idJson 中的属性,则:

showDeleteConfirmation(value, id,idJson,thisHandler) {
  confirm({
    title: 'Voulez vous supprimer cette audio ?',
    content: '',
    okText: 'Oui, je confirme',
    okType: 'danger',
    cancelText: 'Non',
    onOk() {
      deleteMp3Request(id);
      // *** Changes start here ***
      thisHandler.setState(
          // Update callback
          ({extraitMP3: oldExtraitMP3}) => {
              // Clone the object we're changing
              const extraitMP3 = {...oldExtraitMP3};
              // Clone the subobject we're changing and remember it
              const entry = extraitMP3[ids] = {...extraitMP3[ids]};
              // Remove that property from the cloned subobject
              delete entry[isJson];
              // Return the new object with the changes
              return {extraitMP3};
          },
          // State change completion callback
          () => {
              // (Or if you don't want to wait for the state change to complete, you could
              // just put this after the setState call, not in a completion callback
              NotificationManager.success("le fichier audio est supprimé avec succès !", "");
          }
      );
      // *** Changes end here ***
    },
    onCancel() {
    },
  });
}

请注意,在setState 回调 中进行状态更改很重要,您不能进行更改然后调用setState 并返回结果,因为any 当您根据当前状态更新状态时,您需要使用回调形式,因为state updates are asynchronous 并且可能是批处理的。 (否则,您可能会使用陈旧状态进行更新。)

【讨论】:

  • 好的,我读到了。将所有内容都放在 setState 下很聪明,但问题是我在上面做一些映射。使用您的答案,我得到了简单的 ids 和 idJson 未定义
  • 请用minimal reproducible example 来更新您的问题,证明问题,最好是使用堆栈片段([&lt;&gt;] 工具栏按钮)可运行。 Stack Snippets 支持 React,包括 JSX; here's how to do one.
【解决方案2】:

您可以使用回调到setState

thisHandler.setState({extraitMP3: extraitMP3}, () => {
    console.log('extraitMP3',extraitMP3)
    NotificationManager.success("le fichier audio est supprimé avec succès !", "");
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 2017-06-23
    • 2019-08-09
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多