为了账号安全,请及时绑定邮箱和手机立即绑定

使用 usereducer hooks 在过滤器方法中传递 id 时出错

使用 usereducer hooks 在过滤器方法中传递 id 时出错

米琪卡哇伊 2023-10-14 18:39:54
下面的代码面临删除列表的问题。让我知道我做了什么问题。该案例中的问题是删除过滤区域中的部分。传递 id 是问题。请简化问题。函数Reducer Three() {    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
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

你需要通过id行动,而不是通过它。将删除操作更改为:

 <button onClick={() => dispatch({type:'remove', id: item.id})}>close</button>


查看完整回答
反对 回复 2023-10-14
  • 1 回答
  • 0 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信