首页 > 解决方案 > 从特定数组元素发送请求后,如何将文本“发送请求”更改为待处理?

问题描述

我有一个包含许多元素的数组,我在我的组件中使用它的数据,例如姓名、电子邮件等......它还有一个发送请求的按钮,所以当用户点击发送请求时,如果响应返回 true 我想将按钮的文本从 Send 更改为 Pending

我尝试在响应后使用状态,但它将文本更改为所有元素。我只想对单击的元素进行更改。

{this.state.set.map((item, index) => {
return (
{..data}
<Button onPress={() => this.sendRequest(this.state.set[index].id)}>
<Text>Send Request</Text>
</Button>)})}

  sendRequest(UserID) {
        {fetch requests...}
            .then((data) => {
                if (data == true) {
{Change text to Pending}
                }})    }

在服务的响应为 true 之后,我想将按钮的文本更改为等待单击它的特定索引。

标签: javascriptarraysreact-native

解决方案


您只需要在数组上的每个项目的文本上都有一个条件渲染实例。

首先,您需要向数组的每一项添加一个待定变量,这样您就知道需要更改哪个变量。为此,只需执行以下操作:

var pending=this.state.set.map(item=>{
    let obj=item
    obj.pending=false
    return obj
})
this.setState({set: pending})

您需要在代码中的某处运行此函数,例如在 componentDidMount 中。

然后,您需要pending根据索引将键更改为 true。这将成为,在你的 if:

 sendRequest(UserID, index) {              //remember to pass the index
  {fetch requests...}
      .then((data) => {
          if (data == true) {
              let arr=this.state.set
              arr[index].pending=true
              this.setState({ set: arr })
          }
        })    
      } 

然后,文本组件将变为:

<Text>{item.pending? "Pending..." : "Send Request" }</Text>

如果您需要将pending 更改为false,您只需:

toggleOff(index){      //remember to .bind() it
    let arr=this.state.set
    arr[index].pending=false
    this.setState({ set: arr })
}

推荐阅读