首页 > 解决方案 > 使用钩子将值插入数组(反应)

问题描述

所以我有一个对象,我想为数组添加值。

这是我的对象{roomType: t, roomName: n, roomColor: c, appliances:[1] }]),我想在不使用挂钩更改整个对象的情况下为设备添加值。

这是我的整个组件:

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;

在 newAppliances 我想更新房间的电器。

标签: javascripthtmlreactjs

解决方案


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

推荐阅读