首页 > 解决方案 > 使用 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

标签: javascriptreactjsreact-hooks

解决方案


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

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

推荐阅读