简体   繁体   中英

Insert value into a array with hooks (REACT)

So I have an object I want to add value to the array.

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.

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.

I believe in newAppliances method you want to update the appliances for a room, You can do that by doing the following,

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]);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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