我正在尝试将我的Jquery代码转换为React。我有一个表单,当提交时创建多个post请求到不同的网站,并在对应于每个网站的“卡片”中生成每个网站的数据。
我为表单做了一个组件。我也有一个handleSubmit事件,但它只发出一个fetch请求。我想让一个按钮点击多个网站的多个获取请求。
handleSubmit(event) {
event.preventDefault();
this.setState({
input: event.target.value
})
const data = new FormData(event.target);
fetch('/d2s2/L1000', {
method: 'POST',
body: data
})
}
render () {
return (
<div>
<form class="form-inline" role="form">
<div class="form-group" style="text-align:center;">
<select id="memoryType" class="form-control firstList">
<option value="drug" selected="selected">Drug</option>
<option value="disease">Disease</option>
</select>
</div>
<div class="form-group">
<select id="drugInput" class="form-control search-input secondList" name="drug">
</select>
</div>
<button class="form-control" id="submit"><i class="fas fa-search"></i></button>
</form>
</div>
)
}这是我的Jquery:
$("#submit").click(function(e) {
var selectedOption = $('#memoryType option:selected').val();
var text= $("#drugInput option:selected").val();
var search = JSON.stringify({"input": text});
$('.post-load').show();
if (selectedOption.toLowerCase() == "drug") {
$.post("/d2s2/L1000", search, function(data) {
console.log(data);
$(".card-1").html(data);
$('.loader1').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-1 .card-text").html("No significant signatures found");
$('.loader1').fadeOut('fast');
})
$.post("/d2s2/creeds_drugs", search, function(data) {
console.log(data);
$(".card-2").html(data);
$('.loader2').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-2 .card-text").html("No significant signatures found");
$('.loader2').fadeOut('fast');
})
$.post("/d2s2/creeds_diseases", search, function(data) {
console.log(data);
$(".card-3").html(data);
$('.loader3').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-3 .card-text").html("No significant signatures found");
$('.loader3').fadeOut('fast');
})
$.post("/d2s2/geneshot", search, function(data) {
console.log(data);
$(".card-4").html(data);
$('.loader4').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-4 .card-text").html("No significant signatures found");
$('.loader4').fadeOut('fast');
})当我单击submit按钮时,所有的卡都应该向它们各自的端点发出post请求。
发布于 2019-09-07 13:42:21
您可以为请求的每个站点声明一个状态,并分别处理请求,如下所示:
state = {
site1: {},
site2: {}
}
requestSite1 = data => {
fetch('site1Url', {
method: 'POST',
body: data
}).then(res => this.setState({ site1: res }))
}
requestSite2 = data => {
fetch('site2Url', {
method: 'POST',
body: data
}).then(res => this.setState({ site2: res }))
}
async handleSubmit(event) {
event.preventDefault();
this.setState({
input: event.target.value
})
const data = new FormData(event.target);
await this.requestSite1(data);
await this.requestSite2(data);
}并将状态作为道具传递给Card组件,如下所示:
<Card site1Data={this.state.site1} site2Data={this.state.site2} />https://stackoverflow.com/questions/57828421
复制相似问题