如何使用 useState 更新数组?
How do I update an array using useState?
我有以下场景:
DisplayList
组件,呈现列表。列表记录通过 props 传入(这包含列表名称、描述、作者等),以及要列出的初始项目,以及当前 'mode'(可以是 'r'、'g' 或 'a')。该组件显示列表信息,然后为每个列表项渲染一个 DisplayItem
组件。 DisplayItem组件还带了一个回调函数,这样当用户点击列表中的一个item时,就变成'tagged' with the current mode(即item的'mode' 属性改变).
const DisplayList = (props) => {
// Get list object (contains list name etc)
// and current mode (r, a or g)
const { list, currentMode } = props
// Array of items to show
// This is an array of objects, with each object representing a single item
// eg {name: itemname, mode: r}
const [ items, setItems] = useState(props.items)
// Callback function - triggered when the rendered DisplayItem is clicked
// This changes the 'mode' of the item to the current mode
function handleItemClick(index) {
items[index].mode = currentMode
setItems(items) // At this point the list of items should re-render
}
}
return (
<div className="displayItem">
{
items.map(item => <DisplayItem key={uuid()} item={item} handleCellClick={handleItemClick} />)
}
</div>
)
}
我遇到的问题是,单击一个项目似乎会触发 handleItemClick 函数来更新 itemList,但是当它到达 setItems 时,它不会重新呈现。
您没有将索引传递给回调。
试试这个:
items.map({item, index} => <DisplayItem key={uuid()} item={item} handleCellClick={() => handleItemClick(index)} />)
根据 Brian Thompson 在评论中指出的进行编辑
我有以下场景:
DisplayList
组件,呈现列表。列表记录通过 props 传入(这包含列表名称、描述、作者等),以及要列出的初始项目,以及当前 'mode'(可以是 'r'、'g' 或 'a')。该组件显示列表信息,然后为每个列表项渲染一个 DisplayItem
组件。 DisplayItem组件还带了一个回调函数,这样当用户点击列表中的一个item时,就变成'tagged' with the current mode(即item的'mode' 属性改变).
const DisplayList = (props) => {
// Get list object (contains list name etc)
// and current mode (r, a or g)
const { list, currentMode } = props
// Array of items to show
// This is an array of objects, with each object representing a single item
// eg {name: itemname, mode: r}
const [ items, setItems] = useState(props.items)
// Callback function - triggered when the rendered DisplayItem is clicked
// This changes the 'mode' of the item to the current mode
function handleItemClick(index) {
items[index].mode = currentMode
setItems(items) // At this point the list of items should re-render
}
}
return (
<div className="displayItem">
{
items.map(item => <DisplayItem key={uuid()} item={item} handleCellClick={handleItemClick} />)
}
</div>
)
}
我遇到的问题是,单击一个项目似乎会触发 handleItemClick 函数来更新 itemList,但是当它到达 setItems 时,它不会重新呈现。
您没有将索引传递给回调。
试试这个:
items.map({item, index} => <DisplayItem key={uuid()} item={item} handleCellClick={() => handleItemClick(index)} />)
根据 Brian Thompson 在评论中指出的进行编辑