javascript - 使用 usereducer 钩子的过滤方法中的传递 id 错误
问题描述
以下代码面临删除列表的问题。让我知道我做了什么问题。案例中的问题删除过滤器区域中的部分。传递 id 是问题所在。请简化问题。
函数减速器三()
{
const inputRef = useRef();
const initialstate = [{
id: uuid(),
country: "india"
}]
const [items, dispatch] = useReducer((state, action) => {
switch (action.type) {
case'add':
return [
...state,
{
id: uuid(),
country: action.name
}
];
case 'remove':
return state.filter(s => s.id !== action.id);
default:
return state;
}
}, initialstate);
function handleSubmit(event) {
event.preventDefault();
dispatch({
type: 'add',
name: inputRef.current.value
});
inputRef.current.value = '';
}
return (
<div>
<form onSubmit={handleSubmit}>
<input ref={inputRef} />
</form>
<ul>
{items.map((item, index) => (
<li key={item.id}>{item.country}
<button onClick={() => dispatch({type:'remove', index})}>close</button>
</li>
))}
</ul>
</div>
)
}
export default Reducerthree
解决方案
你需要通过id
行动,你没有通过它。将删除操作更改为:
<button onClick={() => dispatch({type:'remove', id: item.id})}>close</button>
推荐阅读
- r - 为什么我收到以下错误 - gsub("^(", x[1, ]) 中的错误:缺少参数 "x",没有默认值
- android - 提高 wrap_content height recyclerview 的性能
- fortran - 派生类型中的参数化过程
- android - objectbox 预填充数据库批量插入
- java - 使用 Gson 将带有嵌套 Map 的 java 类写入自定义 json 格式
- python - 对列进行分组并识别不属于该组的值
- javascript - 如何修改此功能使其也按日期排序?
- xmlhttprequest - IE上子域之间的CORS问题
- elasticsearch - 无法访问 kibana 仪表板
- deployment - .NET 4.7.2 的 VS2017 安装项目