我不确定我在哪里出错,但是当我触发removeTodo动作时,什么也没有发生。我相信这是我过去的错误,但我无法弄清楚。我以为通过将动作设置为将待办事项作为其有效负载,然后在我的调度中将该动作提供给todo.id,它可以删除所说的id。无法完全弄清为什么这行不通。
TodoItem.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { removeTodo } from '../actions';
import '../../css/Todo.css';
const mapDispatchToProps = dispatch => {
return {
removeTodo: todo => dispatch(removeTodo(todo.id))
};
};
const mapStateToProps = state => {
return {todos: [...state.todos]};
};
class ConnectedTodoItem extends Component {
render() {
const {handleToggle, todoId} = this.props;
const mappedTodos = this.props.todos.map((todo, index) => (
<div className='todo-item'>
<span onClick={handleToggle} index={index} id={todoId}>
{todo.title}
</span>
<button type='submit' className='rem-btn' id={todoId} onClick={this.props.removeTodo}>X</button>
</div>
));
return (
mappedTodos
);
}
}
const TodoItem = connect(mapStateToProps, mapDispatchToProps) (ConnectedTodoItem);
export default TodoItem;
reducers.js
import { ADD_TODO } from '../constants/action-types';
import { REMOVE_TODO } from '../constants/action-types';
import uuidv1 from 'uuid';
const initialState = {
todos: []
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos,
{
title: action.payload.inputValue,
id: uuidv1()
}]
}
case REMOVE_TODO:
return {
...state,
todos: [...state.todos.filter(todo => todo.id !== action.payload)]
}
default:
return state;
}
}
export default rootReducer;
actions.js
import { ADD_TODO } from '../constants/action-types';
import { REMOVE_TODO } from '../constants/action-types';
export const addTodo = (todo) => (
{
type: ADD_TODO,
payload: todo
}
);
export const removeTodo = (todo) => (
{
type: REMOVE_TODO,
payload: todo.id
}
)
答案 0 :(得分:2)
要添加到Andy的答案中,似乎您也在提取dispatch调用中的id,但是您已经在actions.js中定义了removeTodo,因此除非您在todo.id中有嵌套的id,否则,您需要将其从任一位置删除。
答案 1 :(得分:1)
乍看之下,问题似乎出在您致电removeTodo
如您所见,该函数接受一个todo
参数,然后从中提取ID。
const mapDispatchToProps = dispatch => {
return {
removeTodo: todo => dispatch(removeTodo(todo.id))
};
};
但是您没有在此处传递待办事项。
onClick={this.props.removeTodo}
尝试以下方法:
onClick={() => this.props.removeTodo(todo)}
更新,以继续威廉的思路。我将进行以下操作,具体绕过id
而不是整个对象。这样一来,您就可以更轻松地了解您要更新的内容。
1)调度功能
const mapDispatchToProps = dispatch => {
return {
removeTodo: id => dispatch(removeTodo(id))
};
};
2)通话功能
onClick={() => this.props.removeTodo(todoId)}
3)行动
export const removeTodo = (id) => (
{
type: REMOVE_TODO,
id
}
)
4)减速器
case REMOVE_TODO: {
return {
...state,
todos: state.todos.filter(todo => todo.id !== action.id)
}
}