当我单击“创建销售订单”按钮时,我进行API调用并将响应打印为有状态组件。但是,我不想更新我的有状态组件,而是想为我收到的每个响应创建一个新段落,因此,如果用户按下按钮5x,他将在响应中包含5个段落。
我该如何实现?我考虑过将响应推送到数组,但我不确定
function ContentFunction () {
const [value, setValue] = useState()
function sendText (data) {
setValue(data)
}
async function handleClick (event) {
switch (event.target.id) {
case 'createSalesOrder':
{
const res = await axios.post('http://localhost:5000/', {
buttonClicked: 'createSalesOrder'
})
sendText(res.data)
break
}
default:
console.log('click didnt work')
}
}
return (
<main>
<div className='container'>
<Form>
<Form.Group>
<Button variant='success' className='button' onClick={handleClick} id='createSalesOrder'>Create Sales Order</Button>
</Form.Group>
</Form>
{/* Here I want to create a new Paragraph for every response instead of just updating this */}
<p>{value}</p>
</div>
</main>
)
}
最佳答案
使用值作为数组
示例代码:
function ContentFunction () {
const [value, setValue] = useState([]) //init with empty array
function sendText (data) {
setValue([...value, data]) //Push new data into array
}
async function handleClick (event) {
switch (event.target.id) {
case 'createSalesOrder':
{
const res = await axios.post('http://localhost:5000/', {
buttonClicked: 'createSalesOrder'
})
sendText(res.data)
break
}
default:
console.log('click didnt work')
}
}
return (
<main>
<div className='container'>
<Form>
<Form.Group>
<Button variant='success' className='button' onClick={handleClick} id='createSalesOrder'>Create Sales Order</Button>
</Form.Group>
</Form>
{/* Here I want to create a new Paragraph for every response instead of just updating this */}
{value.map(item => <p key={value}>{value}</p>)} //render value array
</div>
</main>
)
}
关于javascript - 为每个新州创建一个新段落,而不是更新我的有状态组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60504679/