React中根据下拉框选中值调用对应POST接口并展示结果咨询
实现方案
核心思路
给提交按钮绑定统一触发函数,函数内读取下拉框绑定的this.state.model值,根据值匹配调用对应POST请求即可。
具体实现步骤
- 步骤1:确保下拉框与state正确双向绑定
// 下拉框组件示例,value绑定state.model,选择时自动更新state <select value={this.state.model} onChange={(e) => this.setState({model: e.target.value})} > <option value="值1">值1</option> <option value="值2">值2</option> </select>
- 步骤2:给提交按钮绑定统一调度函数
// 提交按钮绑定这个函数即可 handleSubmit() { // 先设置loading状态、打开弹窗,注意不要直接修改state,要用setState this.setState({ loading: true }, () => { this.openModal(); // 根据下拉框选中值调用对应提交方法 if (this.state.model === '值1') { this.submit(); } else if (this.state.model === '值2') { this.submit1(); } }) }
- 步骤3:修复原有提交代码的逻辑问题
你原有代码里this.state.loading=true是直接修改state不符合React规范,且请求前就应该设置loading状态,调整后代码:
submit(){ const article = { model: this.state.model, dataset:this.state.course, path:this.state.checkbox }; axios.post('http://localhost:3000/home', article) .then(response => this.setState({ s3path: response.data.s3_path, triton_output: response.data.triton_output, confidence: response.data.confidence, inference_model:response.data.inference_model, loading: false, })) .catch(error => { this.setState({ errorMessage: error.message, loading: false }); console.error('There was an error!', error); }); } submit1(){ const article = { model: this.state.model, dataset:this.state.course, path:this.state.checkbox }; axios.post('http://localhost:3000/home', article) .then(response => this.setState({ x: response.data.x, y: response.data.y_output, height: response.data.height, inference_model:response.data.inference_model, loading: false, })) .catch(error => { this.setState({ errorMessage: error.message, loading: false }); console.error('There was an error!', error); }); }
- 步骤4:适配结果展示逻辑
两个接口返回字段不同,渲染时可根据下拉框选中值判断展示对应内容:
// 弹窗内结果展示示例 {this.state.loading ? <p>加载中...</p> : ( <> {/* 值1对应结果展示 */} {this.state.model === '值1' && ( <div> <p>s3路径:{this.state.s3path}</p> <p>推理结果:{this.state.triton_output}</p> <p>置信度:{this.state.confidence}</p> </div> )} {/* 值2对应结果展示 */} {this.state.model === '值2' && ( <div> <p>x坐标:{this.state.x}</p> <p>y坐标:{this.state.y}</p> <p>高度:{this.state.height}</p> </div> )} {this.state.errorMessage && <p style={{color: 'red'}}>请求错误:{this.state.errorMessage}</p>} </> )}
内容的提问来源于stack exchange,提问作者Karthikeyan M
相关产品推荐
相关产品推荐

