這是我的代碼的一部分,它從后端獲取 json api 并呈現為串列。
這是我的 json 資料示例
(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, title: '1?', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
1: {id: 2, title: '2?', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
2: {id: 3, title: '3?', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
3: {id: 4, title: '1?', content: null, createTime: '2021-10-17T14:07:02', updateTime: '2021-10-17T14:07:02', …}
4: {id: 5, title: '2?', content: null, createTime: '2021-10-17T14:07:02', updateTime: '202
這是我下面的問題
const [postId, setPostId] = useState();
return (
<Container>
{list?.map((post, idx) => (
<Content key={idx} onClick={openModal}>
{post.id}
{() => setPostId(post.id)}
{post.title}
</Content>
))}
<Modal data={postId} state={modalState} closeModal={closeModal} />
<div ref={observer} />
<div>{isLoading ? <Loading /> : "Data END"} </div>
</Container>
);
}
export default Posts
我想設定
setPostId
使用價值
{post.id}
在地圖功能中,但我不知道該怎么做?和
{() => setPostId(post.id)}
此功能不起作用
請幫幫我
uj5u.com熱心網友回復:
你可以做 -
{
list?.map((post, idx) => {
setPostId(post.id);
return (
<Content key={idx} onClick={openModal}>
{post.id}
{post.title}
</Content>
);
});
}
但我不確定你為什么要這樣做......
uj5u.com熱心網友回復:
map 不能改變陣列的狀態,因為它回傳一個具有新狀態的新陣列,如果你想改變陣列本身中的一些資料,你需要list.forEach改用
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327786.html
標籤:javascript 反应 功能
