0

我尝试使用 nodejs 和 MongoDB 设置一个简单的 Todolist。

我还使用 useReducer 来简化所有操作并更好地理解它。

我不知道我哪里出错了,但我收到错误“todos.map 不是函数”。我想这与获取数据库列表有关,但我不确定:/

应用程序.js:

import React, { useState, useEffect, useReducer } from "react";
import APIHelper from "./APIHelper.js";
import Todo from './components/Todo'
import "./index.css";

export const ACTIONS = {
  ADD_TODO: 'add-todo',
  TOGGLE_TODO: 'toggle-todo',
  DELETE_TODO: 'delete-todo',
  SET_TODO: 'set-todos'
}

const reducer = (todos, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS: {
      return Object.assign({}, todos, {
        todos: action.payload.todos,
      });
    }
    case ACTIONS.ADD_TODO:
      return ([...todos, newTodo(action.payload.name)])
    case ACTIONS.TOGGLE_TODO:
      return todos.map(todo => {
        if(todo.id === action.payload.id) {
          return { ...todo, complete: !todo.complete}
        }
        return todo;
      })
    case ACTIONS.DELETE_TODO:
      return todos.filter(todo => todo.id !== action.payload.id)
    default: 
      return todos;
    }


}

const newTodo = (name) => {
  return { id: Date.now(), name: name, complete: false }
}


export const setTodos = (todos) => {
  return {
    type: ACTIONS.SET_TODOS,
    payload: {
      todos
    },
  };
};



const App = () => {

  const initialState = {
    todos: []
  };

  
  const [todos, dispatch] = useReducer(reducer, initialState);
  const [name, setName] = useState('');

  useEffect(async () => {
    const fetchTodoAndSetTodo = async () => {
      const todos = await APIHelper.getAllTodos();
      return todos;
    };
    const todos = await fetchTodoAndSetTodo();
    console.log(todos);
    dispatch(setTodos(todos));
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch({ type: ACTIONS.ADD_TODO, payload: {name: name} })
    setName('')
  }

  return (
    
    <div>
      {console.log(todos)};
      <form onSubmit = {handleSubmit}>
        <input type="text" value={name} onChange = {e => setName(e.target.value)}/>
      
      </form>
      {todos.map(todo => {
        return <Todo key={todo.id} todo={todo} dispatch = {dispatch} />
      })}
    </div>
  )
}

export default App;

APIHelper.js:


import axios from "axios";

const API_URL = "http://localhost:8080/todos/";

const createTodo = async (task) => {
  const { data: newTodo } = await axios.post(API_URL, {
    task,
  });
  return newTodo;
};

const deleteTodo = async (id) => {
  const message = await axios.delete(`${API_URL}${id}`);
  return message;
};

const updateTodo = async (id, payload) => {
  const { data: newTodo } = await axios.put(`${API_URL}${id}`, payload);
  return newTodo;
};

const getAllTodos = async () => {
  const { data: todos } = await axios.get(API_URL);
  return todos;
};

export default { createTodo, deleteTodo, updateTodo, getAllTodos };

Todo.js:


import React from "react";
import {ACTIONS} from '../App'

const Todo = ({ todo, dispatch}) => {
  return (
    <div>
        <span style = {{ color: todo.complete ? '#AAA' : '#000'}}>
          {todo.name}
          {console.log(todo.name)}
        </span>
        <button onClick={() => dispatch({ type: ACTIONS.TOGGLE_TODO, payload: {id: todo.id}})}>
          Toggle</button>
        <button onClick={() => dispatch({ type: ACTIONS.DELETE_TODO, payload: {id: todo.id}})}>
          Delete</button>
    </div>
  )}

export default Todo;

我希望有一个人可以帮助我:(

4

2 回答 2

1

在你的减速器中,你试图映射状态对象,但你应该映射todos状态对象的数组:

case ACTIONS.TOGGLE_TODO:
             // todos is actually the state object
      return todos.map(todo => {

您应该:

1.重命名todosstate

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS: {
      return {
        ...state,
        todos: action.payload.todos,
      };
    }
    case ACTIONS.ADD_TODO:
      return {
        ...state,
        todos: [...state.todos, newTodo(action.payload.name)],
      };
    case ACTIONS.TOGGLE_TODO:
      return {
        ...state,
        todos: state.todos.map((todo) => {
          if (todo.id === action.payload.id) {
            return { ...todo, complete: !todo.complete };
          }
          return todo;
        }),
      };
    case ACTIONS.DELETE_TODO:
      return {
        ...state,
        todos: state.todos.filter((todo) => todo.id !== action.payload.id),
      };
    default:
      return state;
  }
};

或者...

2. 将您的状态对象更改为待办事项数组:

 const initialState = [] // todos array
const reducer = (todos, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS: {
      return action.payload.todos;
    }
    case ACTIONS.ADD_TODO:
      return [...todos, newTodo(action.payload.name)];
    case ACTIONS.TOGGLE_TODO:
      return todos.map((todo) => {
        if (todo.id === action.payload.id) {
          return { ...todo, complete: !todo.complete };
        }
        return todo;
      });
    case ACTIONS.DELETE_TODO:
      todos.filter((todo) => todo.id !== action.payload.id);
    default:
      return todos;
  }
};

于 2020-09-27T22:34:13.440 回答
1

问题

你的初始状态是一个对象

const initialState = {
  todos: []
};

但是您的几个减速器案例将状态视为一个数组

const reducer = (todos, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS: {
      return Object.assign({}, todos, {
        todos: action.payload.todos,
      });
    }
    case ACTIONS.ADD_TODO:
      return ([...todos, newTodo(action.payload.name)]) // <-- here
    case ACTIONS.TOGGLE_TODO:
      return todos.map(todo => { // <-- here
        if(todo.id === action.payload.id) {
          return { ...todo, complete: !todo.complete}
        }
        return todo;
      })
    case ACTIONS.DELETE_TODO:
      return todos.filter(todo => todo.id !== action.payload.id) // <-- here
    default: 
      return todos;
    }
}

解决方案

更新 reducer 逻辑以正确访问 todo 状态。我建议将其称为“状态”,然后访问state.todos当前状态值。每个案例都需要返回一个带有todos键的对象。

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS:
      return {
        todos: action.payload.todos,
      });
    
    case ACTIONS.ADD_TODO:
      return {
        todos: [...state.todos, newTodo(action.payload.name)]
      }

    case ACTIONS.TOGGLE_TODO:
      return {
        todos: state.todos.map(todo => {
          if(todo.id === action.payload.id) {
            return { ...todo, complete: !todo.complete}
          }
          return todo;
        })
      }

    case ACTIONS.DELETE_TODO:
      return {
        todos: state.todos.filter(todo => todo.id !== action.payload.id)
      }

    default: 
      return state;
    }
}

您还应该更新您的 UI 逻辑以反映这种嵌套

const [state, dispatch] = useReducer(reducer, initialState);

...

{state.todos.map(todo => {
  return <Todo key={todo.id} todo={todo} dispatch = {dispatch} />
})}

替代解决方案

如果您不打算在减速器状态中存储任何其他内容,那么将您的状态设置为数组可能会更容易一些

更新SET_TODOS动作处理程序以将动作中的待办事项传播(即复制)到新的数组引用中。

const reducer = (todos, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS:
      return [...action.payload.todos]; // <-- spread into array
    
    case ACTIONS.ADD_TODO:
      return [...todos, newTodo(action.payload.name)]

    case ACTIONS.TOGGLE_TODO:
      return todos.map(todo => {
        if(todo.id === action.payload.id) {
          return { ...todo, complete: !todo.complete}
        }
        return todo;
      });
    
    case ACTIONS.DELETE_TODO:
      return todos.filter(todo => todo.id !== action.payload.id)

    default: 
      return todos;
    }
}

更新initialState为空数组。

 const initialState = []; // <-- just the array

现在todos 状态并且只是一个数组,所以任何todos.map都可以按照您的预期工作。

const [todos, dispatch] = useReducer(reducer, initialState);
于 2020-09-27T22:37:50.407 回答