You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux开发Todo应用点击单条删除按钮触发所有确认框弹出问题求助

你现在的全局confirmation状态只是个布尔值,没有关联具体要操作的待办ID,所以状态一旦变成true,所有待办项循环里的确认框判断条件都会命中,自然全部弹出。按下面的步骤修改即可解决:


第一步:修改Reducer逻辑

首先调整初始状态,把confirmation从布尔值改成存储「待确认的待办ID」,初始值为null,同时调整对应action的处理逻辑:

const initalState = {
  todos: [],
  confirmation: null, // 存要确认的todo id,null表示没有要确认的项
}

const reducer = (state = initalState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...state,
        todos: [...state.todos, action.payload],
      }
    case "DELETE_TODO":
      return {
        ...state,
        todos: state.todos.filter(todo => todo.id !== action.payload),
        confirmation: null // 删除完成后自动重置确认状态
      }
    case "CONFIRM":
      return {
        ...state,
        confirmation: action.payload, // 存储当前要确认的todo id
      }
    case "CONTINUE":
      return {
        ...state,
        confirmation: null // 取消确认时重置状态
      }
    default: return state;
  }
}

export default reducer

第二步:修改组件代码

改造handleConfirm方法传递待办ID,同时修改确认框的显示判断逻辑:

import React, {useState, Fragment} from 'react'
import { useDispatch, useSelector } from 'react-redux';
import "./todo.css"

const Todos = () => {
  const dispatch = useDispatch();
  const todos = useSelector(state => state.todos);
  const confirmationSt = useSelector(state => state.confirmation)
  // 改造handleConfirm,把待办id传给action
  const handleConfirm = id => {
    dispatch({
      type: "CONFIRM",  
      payload: id
    })
  }
  const handleContinue = () => {
    dispatch({
      type: "CONTINUE",
    })
  }
  const handleClick = id => dispatch({
    type: "DELETE_TODO",
    payload: id,
  })
  if (!todos || !todos.length) {
    return <p>Empty</p>
  }

  return (
    <ul className='unlist'>
      {todos.map(todo =><Fragment key={todo.id}> 
        <div  className='todoContent'>
          <li >{todo.label}</li>
          <div>
            {/* 点击事件绑定当前todo的id */}
            <button className='delete' onClick={() => handleConfirm(todo.id)}><i className="fas fa-recycle"></i></button> 
            <button className='delete' onClick={() => handleConfirm(todo.id)}><i className="fas fa-wrench"></i></button> 
          </div> 
        </div>
        {/* 仅当待确认id和当前todo id匹配时,才显示确认框 */}
        {confirmationSt === todo.id ? <div className='confirmation-box'>
            Are you sure?
            <button  onClick={() => handleClick(todo.id)}>Yes</button>
            <button onClick={handleContinue}>No</button>
        </div> : null}
      </Fragment>)}
    </ul>
  )   
}

内容的提问来源于stack exchange,提问作者Faruk Suljagic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:18:03