减速机壳体设定值延迟响应

问题描述

当我在按钮单击上调度“ REMOVE_Todo”时,它会执行我想要的操作,而我遇到的问题是它在执行时的问题。它不会返回正确的当前数组长度。

4 is correct number of items in array

现在,当我单击一个项目时,它将分派“ TOGGLE_Todo”,这将更改字体颜色并在文本中插入一行。

items toggled

现在,当切换时,我单击“清除完成”按钮,它将切换“ REMOVE_Todo”,并且工作正常。删除已切换的项目。我遇到的问题是,当我单击一次按钮时,数字无法反映列表中剩余的当前项目数量

incorrect number

但是,如果我再次单击按钮(或多次单击),数字将更新为正确的总数

correct number

这是我的应用代码

b=[]
for i in range(len(l)-1):
    a ={}
    a[s[0]] = l[i][6:14]
    a[s[1]] = l[i][4]
    b.append(a)
# b is your final list of dictionaries
print(b)

这是我的减速器代码

import React,{ useState,useReducer } from 'react';
import { Reducer } from './reducers/reducer';
import './App.css';

function App() {
  const [{ todos,todoCount },dispatch] = useReducer(Reducer,{ 
    todos: [],todoCount: 0,completedCount: 0
  });
  const [text,setText] = useState("");

  return (
    <div className="App">
      <header className="App-header">
        <div>Todo List [ <span style={{color: '#61dafb',margin: '0px',padding: '0px'}}>{ todoCount }</span> ]</div>
        <div>
          { todos.map((todo,index) => (
              <div 
              key={index} 
              onClick={() => dispatch(
                { type: "TOGGLE_Todo",index }
              )}
              style={{
                fontFamily: 'Tahoma',fontSize: '1.5rem',textdecoration: todo.completed ? 'line-through' : "",color: todo.completed ? '#61dafb' : 'dimgray',cursor: 'pointer'
              }}
              >
                { todo.text }
              </div>
            )) 
          }
          <form
            onSubmit={e => {
              e.preventDefault();
              text.length === 0 ? alert("No Task To Add!") : dispatch({ type: "ADD_Todo",text });
              setText("");
            }}
          >
            <input 
              type="text"
              name="input"
              value={ text }
              onChange={e => setText(e.target.value)}
            /><br />
            <button>
              Add
            </button>
          </form>
          <button onClick={() => {dispatch({ type: "REMOVE_Todo" })}}>
            Clear Completed
          </button>
        </div>
      </header>
    </div>
  );
}

export default App;

有人知道我在做什么错,还是我没有做什么?预先感谢!

解决方法

从减速器中删除“ todoCount”,然后使用“ todos”导出计数:

    <div>
      ToDo List [{" "}
      <span style={{ color: "#61dafb",margin: "0px",padding: "0px" }}>
        {todos.filter((todo) => !todo.completed).length}
      </span>{" "}
      ]
    </div>

在CodeSandbox here中查看