简体   繁体   中英

setstate after splice with react

I did a delete that works perfectly using react. Problem is after the delete I want to set the state to the new extraitMP3 to refresh and show automatically results after the Delete. This is the function of the delete :

 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() {
      },
    });
  }

this is the JSON i am mapping :

在此输入图像描述

this is also my return

 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>
    )

Any help would be appreciated.

The problem is that the array you're modifying isn't retained anywhere, it's the array created by Object.keys(extraitMP3[ids].TypeMp3List) , which is temporary unless you save it somewhere.

If the goal is to remove the property with the name in idJson from extraitMP3[ids] , then:

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() {
    },
  });
}

Note that it's important that you make the state changes in the setState callback , you can't make the changes and then call setState with the result, because any time you're updating state based on current state, you need to use the callback form, since state updates are asynchronous and may be batched. (Otherwise, you risk using stale state to do the update.)

You can use callBack to setState .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM