首页 > 解决方案 > 我在 React 中收到此错误 - TypeError: Cannot create property 'completed' on boolean 'true'

问题描述

我正在构建一个“todo”应用程序来练习和学习 React 基础知识。我有一个来自一个名为的文件的对象数组,TodosStores.js我将其传递propsTodoList组件,如下所示:

import TodoList from './components/TodoList';
import TodosStores from './stores/TodosStore';

function App() {
  return (
    <div className="App">
      <TodoList todos={TodosStores} />
    </div>
  );
}

export default App;

现在,我正在尝试将当前的属性值切换todo.completedtrue&false以便我可以删除/添加todo-item-completed该类。但是,我收到此错误:TypeError: Cannot create property 'completed' on boolean 'true'. 我正在寻求一些解释我在这里做错了什么。我来自 Vue 背景,所以可能还有另一种方法可以改变stateReact。

这是我的组件的代码片段:

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.

标签: javascriptreactjsevent-handlingstate

解决方案


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.


推荐阅读