gpt4 book ai didi

javascript - removeTodo 操作未从状态中删除

转载 作者:行者123 更新时间:2023-11-28 17:14:59 27 4
gpt4 key购买 nike

我不确定我哪里出了问题,但是当我触发removeTodo操作时,什么也没有发生。我相信这是我的一个传递错误,但我不太明白。我认为通过将我的操作设置为将 todo 作为其有效负载,然后在我的调度中我向该操作提供 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;

reducer .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
}
)

最佳答案

要添加到Andy的答案中,似乎您还在调度调用中提取了id,但您已经在定义removeTodo的actions.js中执行了此操作,因此除非您在todo.id中有嵌套的id,您需要将其从任一位置删除。

关于javascript - removeTodo 操作未从状态中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53696005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com