通过调度功能更新状态

我正在建立待办事项清单。功能之一是能够通过用户输入将任务添加到任务清单。我正在以减速器模式保存待办事项的初始清单。有一个名为ADD_ITEM的操作应将新任务添加到待办事项列表。但是,此分派功能似乎不起作用。当我单击应该将新任务添加到待办事项列表的按钮时,它只会在列表中添加空白的<li>。当我尝试使用用户输入来添加新的待办事项和应该由输入设置的console.log newItemText时,它将被记录为未定义。有人可以看一下代码,然后告诉我为什么会这样吗?

TodoList.js:

import React,{ useState,useReducer } from"react";

import Todo from "./Todo";
import { initialState,reducer } from "../reducers/todoReducer";
import { ADD_ITEM } from "../actions/actions";


const TodoList = props => {
    const [state,dispatch] = useReducer(reducer,initialState);
    const [newItemText,setNewItemText] = useState("");

    const handleChanges = e => {
        console.log(e.target.value)
        setNewItemText(e.target.vaue);
    };

    console.log(newItemText);

    return (
        <div>
            <ul classname="task-list">
                {state.map(task => (
                    <Todo key={task.item} task={task} />
                ))}
            </ul>
            <input
                classname="add-input"
                name="todo"
                type="text"
                placeholder="Enter a task"
                value={newItemText}
                onChange={handleChanges}
            />
            <button
                classname="add-button"
                onClick={() => dispatch({ type: ADD_ITEM,payload: newItemText })}
            >
                Add a Task
            </button>
            <button
                classname="add-button"
                onClick={null}
            >
                Remove Completed
            </button>
            </div>
    )
}

export default TodoList;

todoReducer.js:

import { ADD_ITEM,TOGGLE_COMPLETED,REMOVE_COMPLETED } from "../actions/actions";

export const initialState = [
    { item: 'Learn about context API',completed: false,id: 1},{ item: 'Learn about reducers',id: 2},{ item: 'complete context API project',id: 3},{ item: 'complete reducers project',id: 4}
];

export const reducer = (state = initialState,action) => {
    console.log(action)
    switch(action.type) {
        case ADD_ITEM:
            return [
                ...state,{
                    item: action.payload,id: Date.now()
                }
            ]
        case TOGGLE_COMPLETED:
            const toggledState = [...state];
            toggledState.map(item => {
                if(item.id === action.payload) {
                    item.completed = !item.completed;
                }
            })
            state = toggledState;
            return state;
        case REMOVE_COMPLETED:
            return state.filter(item => !item.completed);
        default:
            return state;
    }
}
heiheiliangliang 回答:通过调度功能更新状态

handleChanges函数中,您拼错了value

setNewItemText(e.target。 vaue );

;)

本文链接:https://www.f2er.com/2721544.html

大家都在问