我有一些简单的字段。我希望根据从axios响应中获取的数据填充输入框。请参见下面的图片。
我正在使用hooks将数据保存到状态中。 我的问题是,如何在点击“获取详细信息”按钮时填充输入框(来自API的响应)。
请参见以下代码:
const [data, setData] = useState([])
const [advisoryDetails, setadvisoryDetails] = useState({
ADVISORYID: '',
ADVISORYDESC: '',
CREATEDBY:'',
MODIFIEDBY:'',
STATUS1: ''
})
const [advisoryDetails1, setadvisoryDetails1] = useState([])
const [advisoryID, setadvisoryID] = useState('')
const getAdvisoryTest = async () => {
await axios.post('/API',advisoryID)
.then(response => {
console.log(response.data)
setData(response.data)
console.log('data',data)
setadvisoryDetails1(response.data)
console.log('advisoryDetails1',advisoryDetails1)
alert('success')
})
advisoryDetails1.map(adv => {
advisoryDetails.ADVISORYID = adv.ADVISORYID;
advisoryDetails.ADVISORYDESC = adv.ADVISORYDESC;
advisoryDetails.CREATEDBY = adv.CREATEDBY;
advisoryDetails.MODIFIEDBY = adv.MODIFIEDBY;
if(adv.CREATEDBY && adv.MODIFIEDBY != '')
{
advisoryDetails.STATUS1 = 'Modified'
}
else{ advisoryDetails.STATUS1 = 'New'}
console.log('populate',advisoryDetails)
})
}
const txtAdvIdOnChange = e =>{
setadvisoryID(prevState =>({
...prevState,
'ADVISORYID':e.target.value
}));
console.log('onChange ID:',advisoryID)
}
return(
<div>
<label>AdvisoryID: </label>
<input type='text' placeholder='Advisory ID' className='txtAdvisoryID' onChange={txtAdvIdOnChange} />
<button onClick={()=>getAdvisoryTest()}>Get Details</button>
<br /><br />
<label>Advisory Desc: </label>
<input type='text' placeholder='textbox1' className='txtAdvisoryDesc' value={advisoryDetails&&advisoryDetails.ADVISORYDESC} disabled/>
<br/>
<label>New / Modified: </label>
<input type='text' placeholder='textbox2' className='txtStatus' value={advisoryDetails&&advisoryDetails.STATUS1} disabled/>
</div>)
在那些代码中,输入框没有被填充,即使在console.log中也是如此。 希望我能帮到你,谢谢。
advisoryDetails.STATUS1 = 'Modified'
?使用setadvisoryDetails
来更新状态,像这样:setadvisoryDetails(prevState => ({...prevState, STATUS1: "Modified"}))
。 - Haseeb AhmadadvisoryDetails1
,它只会覆盖数据到advisoryDetails
,因此你将看到最后一次迭代的值。 - Haseeb Ahmadresponse.data
设置为advisoryDetails1
,那么为什么不使用响应的数据来更新它,因为此时可能advisoryDetails1
尚未更新。const respData = response.data; if (respData.length > 0) { const adv = respData[respData.length-1]; setadvisoryDetails((prevState) => ({ ...prevState, ...adv, STATUS1: adv.CREATEDBY && adv.MODIFIEDBY != '' ? '已修改' : '新建' })) }
- Haseeb Ahmad