我正在學(xué)習(xí)反應(yīng),我正在制作一個(gè)簡(jiǎn)單的 ToDoApp。我在我的 App 組件的狀態(tài)下從 JSON 文件中設(shè)置了一些待辦事項(xiàng)數(shù)據(jù),并使用這些值來(lái)填充子組件。我編寫(xiě)了一個(gè)方法,每次在復(fù)選框元素上觸發(fā) onChange 事件時(shí)都會(huì)調(diào)用該方法,并通過(guò)更新?tīng)顟B(tài)來(lái)翻轉(zhuǎn)復(fù)選框。事情是這段代碼以前工作得很好,但現(xiàn)在不行了。當(dāng)我更改復(fù)選框時(shí),狀態(tài)會(huì)相應(yīng)更新,但它不會(huì)在子元素中更新,我想知道為什么。這是我的代碼應(yīng)用程序.jsimport 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;待辦事項(xiàng).jsimport 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;
狀態(tài)更改后子組件未更新
繁華開(kāi)滿(mǎn)天機(jī)
2021-06-29 17:39:28