我不确定这里哪里出错了,但是当我触发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
}
)
最佳答案
乍看之下,问题似乎与您呼叫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)
}
}
关于javascript - removeTodo Action 未从状态中移除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53696005/