无法使用 setState 更新对象属性



我正在创建一个简单的应用程序。我在BulletinsList.js中存储我的卡片/公告,并在bulletin .js中存储单个公告/卡片。

我正在尝试更改"Hello World"(在bulletin .js中使用输入,通过点击标题并将其切换到输入)标题在第一个公告,但没有任何工作,所以基本上我不能更新存储在数组中的对象的属性。我传递了一个对象id,但它不能正常工作。谁能给我一个答案,我该怎么做?

BulletinList.js

import React, { Component } from 'react';
import Bulletin from '../Bulletin/Bulletin';
class BulletinList extends Component {
state = {
bulletin: [
{
id: 1,
title: 'Hello World',
listOfTasks: ['eat sandwich', 'clean house']
},
{
id: 2,
title: 'Hello Mars',
listOfTasks: ['eat spaghetti', 'go to sleep']
},
],
titleField: '',
descriptionField: ''
}

addEmptyCard = () => {
this.setState({
bulletin: [...this.state.bulletin, {id: this.state.bulletin.length + 1, title: '...', listOfTasks: []}]
})
}
captureInput = (event, id) => {
const specificCard = this.state.bulletin[id - 1];
this.setState(prevState => ({
[specificCard]: {                 
...prevState.specificCard,    
title: event.target.value    
}
}))
}


render() {
return(
<div>
<button onClick={this.addEmptyCard}>+</button>
{this.state.bulletin.map((element => {
return <Bulletin 
id={element.id} 
title={element.title} 
list={element.listOfTasks}
captureInput={this.captureInput}/>
}))}
</div>
)
}
}
export default BulletinList;

Bulletin.js

import React, { useState } from 'react';
const Bulletin = ({ id, title, list, captureInput }) => {
const [inputOn, setInputOn] = useState(false);
return(
<div>
{!inputOn ? <h1 onClick={() => setInputOn(!inputOn)}>{title}</h1> 
: 
<div>
<input type="text" onChange={(event) => captureInput(event, id)}/>
<button onClick={() => setInputOn(!inputOn)}>Change title</button>
</div>}
{list.map(element => {
return <p>{element}</p>
})}
<input type="text" />
</div>
)
}
export default Bulletin;

captureInput中,您不重写bulletin属性,而是创建一个新的,而不是使用对象作为索引。解决这个问题的正确方法之一是:

captureInput = (event, id) => {
const newBulletin = [...this.state.bulletin];
newBulletin[id - 1].title = event.target.value;
this.setState({
bulletin: newBulletin
});
}

我在这里使用扩展语法创建一个新的数组,然后覆盖元素在给定位置的title属性。

同样,您将元素的id传递给Bulletin组件,然后将其用作索引。当标识符是有序的时候,它现在可以工作,但是最好通过迭代数组来找到真正的索引:

captureInput = (event, id) => {
const elemIndex = this.state.bulletin.findIndex(elem => elem.id === id);
const newBulletin = [...this.state.bulletin];
newBulletin[elemIndex].title = event.target.value;
this.setState({
bulletin: newBulletin
});
}

这样你就可以在不破坏应用程序的情况下删除项。

最新更新