gpt4 book ai didi

javascript - 数组中每个元素的新段落

转载 作者:行者123 更新时间:2023-12-02 21:35:21 24 4
gpt4 key购买 nike

我有一个有状态组件,它从 api 调用获取数据。我想为该数组的每个项目打印一个新段落。现在它为每个项目打印一个新段落,但该段落包含整个数组..

 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 Entry of the Array
{value.map(item => <p key={value}>{value}</p>)} //render value array
</div>
</main>
)
}

最佳答案

你就快到了

                                    //change this from `value` to `item`
{value.map(item => <p key={value}>{item}</p>)}

在映射中,第一个参数(在您的情况下为 item)是当前迭代中的元素。

您还可以传递第二个参数,该参数将是可用于 key 的索引,如下所示

 {value.map((item,index) => <p key={index}>{item}</p>)}

(请注意参数 item,index 周围添加的 ())

关于javascript - 数组中每个元素的新段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60512137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com