arrays - 在 React 中更新对象数组值的最佳方法是什么
问题描述
我的反应state
:
//...
this.state = {
mylist: [
{
"id": 0,
"trueorfalse": false
},
{
"id": 1,
"trueorfalse": false
}
]
}
//...
我正在尝试trueorfalse
根据id
这是我到目前为止所做但没有奏效的方法:
var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
var TorF = true
if (type === 1) {
this.setState({
mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { TorF }) : el))
})
}
我真的想让它变得动态,所以它trueorfase
会与现在相反:
var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
if (type === 1) {
this.setState({
mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { /* if already true set to false or vice versa */ }) : el))
})
}
如何更新我的代码以具有第二个示例中显示的动态性(如果可能),否则第一个示例会很好
解决方案
另一种解决方案使用map
:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
mylist: [
{
id: 0,
trueorfalse: false
},
{
id: 1,
trueorfalse: true
}
]
};
}
toggleBoolean = () => {
const ID = Number(this.state.selectedID);
this.setState(prevState => ({
mylist: prevState.mylist.map(item => {
if (item.id === ID) {
return { ...item, trueorfalse: !item.trueorfalse };
} else {
return item;
}
})
}));
};
render() {
return (
<div className="App">
<p>{`State values: ${JSON.stringify(this.state.mylist)}`}</p>
<button onClick={this.toggleBoolean}>Change true/false values</button>
<label>Insert ID:</label>
<input
type="number"
onChange={event => this.setState({ selectedID: event.target.value })}
/>
</div>
);
}
}
推荐阅读
- opencv - 如何重新创建此边缘平滑图像过滤器?
- reactjs - 你如何在 Scrimba 中使用 node-sass 作为 React 模板中的依赖项?
- c# - 无法理解如何访问列表中的嵌套列表
- excel - 过滤数据并将其从多张工作表复制到一张工作表
- php - 之前如何发送自定义消息,代理会话发送实际消息
- laravel - 使用 Laravel-Websockets 向特定用户发送消息(一对一聊天)
- android - startAfter() 方法使应用程序 Firestore 数据库崩溃
- c# - 如何存储引用以避免在c#中解构
- html - 绝对定位的子 div 离开父 div
- python - 如果超过 x 个字符,如何从文件中删除行