简体   繁体   English

使用钩子将值插入数组(反应)

[英]Insert value into a array with hooks (REACT)

So I have an object I want to add value to the array.所以我有一个 object 我想为数组添加值。

This is my object {roomType: t, roomName: n, roomColor: c, appliances:[1] }]) I want to add values to the appliances without changing the whole object with hooks.这是我的 object {roomType: t, roomName: n, roomColor: c, appliances:[1] }])我想在不改变整个 ZA8CFDE6331BD59EB2666666ZZ 的情况下为设备添加值。

This is my whole component:这是我的整个组件:

 function App(props) { const [rooms, setRooms] = useState([ {roomType:'bedroom', roomName: "snir", roomColor: "blue"} ]) let NewRoom = (t,n,c) => { setRooms([...rooms,{roomType: t, roomName: n, roomColor: c, appliances:[1] }]) } let newAppliances = (a,n) => { rooms.map((item) =>{ if(n === item.name){ item.appliances.push(a) } }) } console.log(rooms) const [indexRoom, setIndexRoom] = useState([]) let chack = (rIndex,rName,rType) =>{setIndexRoom([rIndex, rName,rType])} return ( <div className="App"> <Router> <Switch> <Route exact path = '/' > <Home arr = {rooms} func = {chack} /> </Route> <Route path = '/addroom' render= { (props) =><AddNewRoom add = {NewRoom}{...props}/>}/> <Route path = '/room'> <Rooms arr = {rooms} index = {indexRoom[0]} name = {indexRoom[1]} type = {indexRoom[2]} funcApp = {newAppliances} /> </Route> </Switch> </Router> </div> ); } export default App;

in newAppliances I want to update the appliances for a room.在 newAppliances 我想更新房间的电器。

I believe in newAppliances method you want to update the appliances for a room, You can do that by doing the following,我相信newAppliances方法你想更新一个房间的电器,你可以通过执行以下操作来做到这一点,

let newAppliances = (a,n) => {
    const index = rooms.findIndex(item => item.name === n);
    if(index > -1) {
       if(rooms[index].hasOwnProperty(appliances) && rooms[index].appliances.length > 0) {
           rooms[index].appliances.push(a);  
       }
       else rooms[index].appliances = [a];    
    }
    setRooms([...rooms]);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM