所以我尝试从Redux store
中删除一些元素。正如我从其他关于SOF的问题中看到的那样,最好和最简单的方法是使用arry filter
方法。但是我遇到的问题 - 该方法只是删除了Redux store
中的所有数组。
我错过了什么?谢谢。
/ * REDUCER * /
import { ADD_TODO, DELETE_TODO } from '../Variables/Variables'
const initialState = {
todos: []
}
function TodoApp(state, action) {
if (typeof state === 'undefined') {
return initialState;
}
switch (action.type) {
case ADD_TODO:
return Object.assign([], state, {
todos: [
...state.todos,
{
id: action.id,
text: action.text
}
]
});
case DELETE_TODO:
return state.todos.filter(todos => todos.id !== action.id);
default:
return state;
}
}
export default TodoApp;
/ * CONTAINER * /
import { connect } from 'react-redux';
import TodoList from '../Components/TodoList/TodoList';
import { DeleteTodo } from '../Actions/AddTodo'
const mapStateToProps = state => ({
todos: state.todos
});
const mapPropsToDispatch = dispatch => {
return {
todoFormDelete: todo => dispatch(DeleteTodo(todo))
}
}
export default connect(
mapStateToProps,
mapPropsToDispatch)(TodoList)
/ * COMPONENT * /
import React from 'react';
import TodoIteam from '../TodoIteam/TodoIteam'
class TodoList extends React.Component {
handleDelete = (e) => {
let target = e.target;
let closest = target.closest('span');
if (!closest) { return }
let index = closest.parentNode.getAttribute('index');
this.props.todoFormDelete(index);
}
render(props) {
return (
<ul onClick={this.handleDelete}>{this.props.todos.map((iteam, index) =>
<TodoIteam key={iteam.id} {...iteam} />
)}
</ul>
);
}
}
export default TodoList;
UPD / *行动* /
import { ADD_TODO, DELETE_TODO } from '../Variables/Variables'
let nextTodoId = 0;
function AddTodo(text) {
return {
id: nextTodoId++,
type: ADD_TODO,
text
}
};
function DeleteTodo(id) {
return {
type: DELETE_TODO,
id
}
};
export { AddTodo, DeleteTodo }
答案 0 :(得分:0)
case DELETE_TODO:
return Object.assign({}, {todos: state.todos.filter(todo => todo.id !== action.id)})
答案 1 :(得分:0)
解决:
问题在于传输action.id
。它与string
值一样进入reducer,因此过滤器不会如何处理digits
和string
。
我只是包裹parseInt(action.id)
并开始正常工作。