javascript - 我在 React 中收到此错误 - TypeError: Cannot create property 'completed' on boolean 'true'
问题描述
我正在构建一个“todo”应用程序来练习和学习 React 基础知识。我有一个来自一个名为的文件的对象数组,TodosStores.js
我将其传递props
给TodoList
组件,如下所示:
import TodoList from './components/TodoList';
import TodosStores from './stores/TodosStore';
function App() {
return (
<div className="App">
<TodoList todos={TodosStores} />
</div>
);
}
export default App;
现在,我正在尝试将当前的属性值切换todo.completed
为true
&false
以便我可以删除/添加todo-item-completed
该类。但是,我收到此错误:TypeError: Cannot create property 'completed' on boolean 'true'
. 我正在寻求一些解释我在这里做错了什么。我来自 Vue 背景,所以可能还有另一种方法可以改变state
React。
这是我的组件的代码片段:
import React, { Component } from 'react';
import './TodoListStyles.css'
class TodoList extends Component {
constructor(props){
super(props);
this.state = { todos: this.props.todos }
this.handleChange = this.handleChange.bind(this);
}
handleChange(item) {
return item.completed = !item.completed
}
render() {
return (
<ul className='todo-list'>
{
this.props.todos.map(
todo =>
<React.Fragment key={todo.id}>
<li className={`todo-item ${todo.completed ? 'todo-item-completed' : ''}`}>{ todo.title }</li>
<input type='checkbox' onChange={this.handleChange(todo.completed)} checked={todo.completed} />
</React.Fragment>
)
}
</ul>
)
}
}
export default TodoList;
PS: I'm using React Class Components because I want to contribute to an open-source project which uses class components. I might try refactoring later to hooks.
解决方案
The reason you are getting error TypeError: Cannot create property 'completed' on boolean 'true'
is because you are passing boolean value to handleChange
in onChange={this.handleChange(todo.completed)}
and in the function you are creating/mutating item.completed
.
It can not create property completed
on true
or false
basically.
推荐阅读
- ios - 如何使用客户的开发者帐户将应用程序发布到 App Store?
- xcode - LaunchScreen.storyboard 未显示
- python - 朴素高斯预测概率仅返回 0 或 1
- python - Python:标记关键字并使用 1 和 0 创建新的标签列
- python - 如何使用来自 stripe webhook ex) 订阅、django 中的客户的数据更新当前登录用户的字段?
- sql - SQL左连接仅在我指定右表的列时才有效(Redshift)
- ios - 弹出框透明度问题仅适用于 iPhone 11 和 Max 版本
- java - Flyway 不会将值插入数据库
- r - R - 来自多个 csv 的列表列表,具有多个标题,列数和顺序不一致
- flutter - 应用程序重新启动后无法从 Hive 检索数据