[英]Not able to add todo in a todo-list using react and redux. What am I doing wrong?
render() {
const listItems = this.props.todos.map((todo) =>
<ListItem key={todo.id} id={todo.id} content={todo.content} onEdit={this.onEditItem}/>
)
return <>
<ul className="todo-list">
{listItems}
</ul>
{/* <AddItem/> */}
<div className="add-item">
<input type="text" onChange={this.onChangeValue}/>
<button type="submit" onClick={this.onAddItem}>Add Item</button>
</div>
</>
}
onAddItem = () => {
this.props.submitNewTodo({ id: this.props.todos.length + 1, content: this.state.value})
};
When I console.log this.props.todos.length
it returns the value 2 and this.state.value
returns the value typed into the input.当我 console.log
this.props.todos.length
它返回值 2 并且this.state.value
返回输入到输入中的值。 But the "Add Item" button doesn't work.但是“添加项目”按钮不起作用。
I have mapped submitNewTodo
to dispatch addTodo(newTodo)
like so我已经将
submitNewTodo
映射到像这样调度addTodo(newTodo)
const mapDispatchToProps = (dispatch) => {
return {
submitNewTodo: function(newTodo) {
dispatch(addTodo(newTodo));
}
}
}
Complete code is in this codepen.完整的代码在这个 codepen 中。
https://codepen.io/blenderous/pen/MWjdyoN?editors=0011 https://codepen.io/blenderous/pen/MWjdyoN?editors=0011
Your addTodo
action creator is wrong:您的
addTodo
操作创建者是错误的:
const addTodo = (todo) => {
type: 'ADD_TODO',
todo
};
this is a method that treats这是一种治疗方法
type: 'ADD_TODO',
todo
as a method body.作为方法体。 (
type
being used as the break label for the string 'ADD_TODO'
, followed by todo
) (
type
被用作字符串'ADD_TODO'
的中断 label ,后跟todo
)
If you want to return an action, these two notations are correct:如果你想返回一个动作,这两个符号是正确的:
const addTodo = (todo) => {
return {
type: 'ADD_TODO',
todo
}
};
// note the parantheses!
const addTodo = (todo) => ({
type: 'ADD_TODO',
todo
});
The first thing I notice with your code is that your reducer is not following the pattern Redux uses.我注意到你的代码的第一件事是你的减速器没有遵循 Redux 使用的模式。
const todoReducer = ( state = [{ id: 1, content: "Call Client" },
{ id: 2, content: "Write Log" }], action ) => {
if (action.type == ADD_TODO) {
return state.concat(action.todo);
}
else {
return state;
}
}
The first rule that it breaks is that this should be a switch, not an if statement.它打破的第一条规则是这应该是一个开关,而不是一个 if 语句。
switch (action.type) {
case 'ADD_TODO':
// create new todos with the added todo
const newTodos = [
...state.todos,
action.payload.todo,
]
// new state object
return {
...state,
todos: newTodos,
}
default:
return {
...state,
}
}
The second rule is that you want to always have a payload property to follow the proper flux patterns.第二条规则是您希望始终具有有效负载属性以遵循正确的通量模式。 That payload would contain all of your data.
该有效负载将包含您的所有数据。
const addTodo = (todo) => {
type: 'ADD_TODO',
payload: {
todo,
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.