ReactJS中使用axios发起post请求时如何动态获取按钮id值
实现方案
步骤1:新增存储选中id的状态
如果是类组件,在state中新增字段:
// 类组件state定义 state = { // 保留原有其他state字段,比如question、answer、isOpenTwo等 selectedIpoId: null }
如果是函数式组件,新增useState:
const [selectedIpoId, setSelectedIpoId] = useState(null)
步骤2:修改按钮点击事件,传递当前项id
修改按钮的onClick回调,把当前行的data.id传入打开弹窗的方法:
<Button variant="outlined" color="primary" id={data.id} onClick={() => handleDialogOpenTwo(data.id)}> Faq </Button>
步骤3:修改弹窗打开方法,存储选中的id
在打开弹窗的逻辑中,把传入的id存入之前声明的状态:
类组件写法
handleDialogOpenTwo = (id) => { this.setState({ selectedIpoId: id, isOpenTwo: true }) }
函数式组件写法
const handleDialogOpenTwo = (id) => { setSelectedIpoId(id) setIsOpenTwo(true) }
步骤4:替换POST请求中的ipoId取值
把POST请求里写死的'1511'替换为状态中存储的选中id即可:
类组件写法
axios.post('https://gatewayapi.invest19.com/api/faqs', { ipoId: this.state.selectedIpoId, faqList:[ { question: this.state.question, answer: this.state.answer, } ] } )
函数式组件写法
axios.post('https://gatewayapi.invest19.com/api/faqs', { ipoId: selectedIpoId, faqList:[ { question: question, answer: answer, } ] } )
补充说明
如果<FaqPage />是独立子组件,注意通过props把question、answer的状态同步方法传递给子组件,保证提交时能拿到正确的输入内容。
内容的提问来源于stack exchange,提问作者govind jha
相关产品推荐
相关产品推荐

