Javascript 如何在对象数组中设置项的状态
我有一个对象数组 我想在我的组件中显示这些对象,并想创建一个函数,以便在单击按钮时将Javascript 如何在对象数组中设置项的状态,javascript,arrays,reactjs,object,Javascript,Arrays,Reactjs,Object,我有一个对象数组 我想在我的组件中显示这些对象,并想创建一个函数,以便在单击按钮时将seen:0更改为seen:1 var historyNotif = [ {id: 66, seen: 0, tourist_full_name: "Khouloud Ben Abddallah"}, {id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez"}, {id: 103, seen: 0, tourist_full_name:
seen:0
更改为seen:1
var historyNotif = [
{id: 66, seen: 0, tourist_full_name: "Khouloud Ben Abddallah"},
{id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez"},
{id: 103, seen: 0, tourist_full_name: "Harry Paz Galvez"},
]
我试过这个,但不起作用:
isSeen() {
this.setState(() => ({
historyNotif: {
...this.state.historyNotif,
seen: 1
}
}));
}
怎么做
isSeen=(id)=>{
let {historyNotif}=this.state
historyNotif.map(each=>each.id===id?each.seen=1:null)
this.setState({historyNotif})
}
调用此函数并将id作为参数传递,该参数已存在
如果要更改所有对象的可见状态。
你可以像我一样
isSeen=()=>{
let {historyNotif}=this.state
historyNotif.map(each=>each.seen=1);
this.setState({historyNotif}
}
您可以将通知保持在组件状态,并通过渲染中的此通知进行映射,您可以生成一些html,并在那里触发事件以更新所看到的值
import React,{Component}来自“React”;
类应用程序扩展组件{
状态={
通知:[
{id:66,seen:0,游客全名:“Khouloud Ben Abddalah”},
{id:102,seen:0,游客全名:“Harry Paz Galvez”},
{id:103,SEED:0,游客全名:“哈里·帕斯·加尔维斯”}
]
};
handleClick=id=>{
console.log(id);
const updateItems=this.state.notifications.map(项=>{
如果(item.id==id){
返回{…项,见:1};
}
退货项目;
});
这是我的国家({
通知:updatedItems
});
};
render(){
返回(
{this.state.notifications.map(项=>{
返回(
this.handleClick(item.id)}>
{item.tourism_full_name}-{item.seen?“seen”:“notseen”}>
);
})}
);
}
}
导出默认应用程序;
发布一些您需要的代码did@PraveenGopal检查问题我已经更新了