在React Hooks / Redux应用程序中删除特定列表项的方法有多种。以下是一种常见的做法:
useSelector
钩子函数从Redux store中获取数据。useDispatch
钩子函数来派发Redux action。dispatch
函数来派发一个删除列表项的action。该action应该包含要删除的列表项的唯一标识符。filter
函数来过滤掉要删除的列表项。下面是一个示例代码:
// Redux reducer
const initialState = {
items: []
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_ITEM':
return {
...state,
items: [...state.items, action.payload]
};
case 'DELETE_ITEM':
return {
...state,
items: state.items.filter(item => item.id !== action.payload)
};
default:
return state;
}
};
// React component
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const MyComponent = () => {
const items = useSelector(state => state.items);
const dispatch = useDispatch();
const deleteItem = (itemId) => {
dispatch({ type: 'DELETE_ITEM', payload: itemId });
};
return (
<div>
{items.map(item => (
<div key={item.id}>
<span>{item.name}</span>
<button onClick={() => deleteItem(item.id)}>Delete</button>
</div>
))}
</div>
);
};
这是一个简单的示例,展示了如何使用React Hooks和Redux来删除特定列表项。你可以根据自己的需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云