javascript - 从特定数组元素发送请求后,如何将文本“发送请求”更改为待处理?
问题描述
我有一个包含许多元素的数组,我在我的组件中使用它的数据,例如姓名、电子邮件等......它还有一个发送请求的按钮,所以当用户点击发送请求时,如果响应返回 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 之后,我想将按钮的文本更改为等待单击它的特定索引。
解决方案
您只需要在数组上的每个项目的文本上都有一个条件渲染实例。
首先,您需要向数组的每一项添加一个待定变量,这样您就知道需要更改哪个变量。为此,只需执行以下操作:
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 })
}
推荐阅读
- php - 如果之前在 WooCommerce 上购买过产品,请避免客人购买
- python - 我在尝试将标记词列表转换为 Python 中的字符串时遇到了这个问题
- python - 我如何到达每次会员健康下降的地方?
- javascript - 无法从 CDN 使 vue-slick-carousel 工作
- c++ - 不确定使用函数宏作为 C++ 程序入口点的概念,
- python - Selenium 只打印一个输出
- python - 显示实时时钟并检查字符串长度
- reactjs - 如何在 React 移动应用上实现导航
- sql - 不同行的多重条件
- javascript - 如何在 react-js 中一次选择所有图像?