开关案例语句react-redux的语法错误

时间:2018-12-07 16:21:12

标签: javascript syntax react-redux switch-statement case

在我的代码中,action.payload指向一个todo.index,因此,如果我的REMOVE_TODO案例与该事件被触发的索引相同,则应该过滤出一个todo。但是,我到处都出现语法错误。我已经弄乱了包装,甚至尝试从头开始重写它,但是无法消除这些语法错误。有人看到我在这里想念的东西吗? 请让我知道是否需要更多信息。谢谢大家!

import { ADD_TODO } from '../constants/action-types'; 
import { REMOVE_TODO } from '../constants/action-types';

const initialState = {
  todos: []
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TODO:
    return {
        ...state,
        todos: [...state.todos, action.payload]
    }

    case REMOVE_TODO:
    return {
      ...state,
      todos: [...state.todos.filter((todo, i) => {i  !== action.payload})]
    }

    default:
      return state;
  }
}

export default rootReducer;

2 个答案:

答案 0 :(得分:0)

好吧,您错过了在过滤器函数内返回值的操作。

看一下演示。

const initialState = {
  todos: [1,2,3,7,8,5]
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TODO':
    return {
        ...state,
        todos: [...state.todos, action.payload]
    }

    case 'REMOVE_TODO':
    return {
      ...state,
      todos: [...state.todos.filter((todo, i) => i  !== action.payload)]
    }

    default:
      return state;
  }
}

let op = rootReducer({todos:[1,2,3,4,5,6]},{type:'REMOVE_TODO',payload:1});
console.log(op)

答案 1 :(得分:0)

结果是我只是从我的filter方法返回一个对象。 todos: [...state.todos.filter((todo, i) => {i !== action.payload})] 只需从箭头函数的返回处除去大括号,一切都很好。