状态更改后子组件未更新

我正在学习反应,我正在制作一个简单的 ToDoApp。我在我的 App 组件的状态下从 JSON 文件中设置了一些待办事项数据,并使用这些值来填充子组件。我编写了一个方法,每次在复选框元素上触发 onChange 事件时都会调用该方法,并通过更新状态来翻转复选框。事情是这段代码以前工作得很好,但现在不行了。当我更改复选框时,状态会相应更新,但它不会在子元素中更新,我想知道为什么。这是我的代码


应用程序.js


import React from "react";

import TodoItem from "./TodoItem";

import toDoData from "./toDosData";


class App extends React.Component {

    constructor() {

        super();

        this.state = {

            toDoData: toDoData

        };

        this.handleOnChange = this.handleOnChange.bind(this);

    }


    handleOnChange(key)

    {

        this.setState(prevState => {

            let newState = prevState.toDoData.map(currentData => {

                if(currentData.id === key)

                    currentData.completed = !currentData.completed;

                return currentData;

            });

            return {toDoData: newState};

        });

    }


    render() {

        let toDoComponents = this.state.toDoData.map(toDoDatum =>

            <TodoItem key={toDoDatum.id} details={{

                key: toDoDatum.id,

                text: toDoDatum.text,

                completed: toDoDatum.completed,

                onChange: this.handleOnChange

            }} />);

        return (

            <div>

                {toDoComponents}

            </div>

        );

    }

}


export default App;

待办事项.js


import React from "react";


class TodoItem extends React.Component {


    properties = this.props.details;


    render() {

        return (

            <div>

                <input type="checkbox" checked={this.properties.completed}

                    onChange={() => this.properties.onChange(this.properties.key)}

                />

                <span>{this.properties.text}</span>

            </div>

        )

    }

}


export default TodoItem;


繁华开满天机
浏览 161回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript