javascript - 使用钩子将值插入数组(反应)
问题描述
所以我有一个对象,我想为数组添加值。
这是我的对象{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 我想更新房间的电器。
解决方案
我相信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]);
}
推荐阅读
- sapui5 - 搜索帮助在 UI5 中没有给出准确的结果
- openstack-nova - 如何使用 openstack 上的当前环境附加浮动 IP
- python - 如果条件为真,如何组合列表项而不是重复
- azure - 为什么项目找不到 WebJobs.Core 的引用?
- javascript - 为什么光滑的滑块向前和向后滑动滑动?
- linux - /dev/ttyACM0 和 /dev/ttyACM1 的文件描述符相同
- c# - 如何在 XAML 中重新加载图像?
- javascript - React / CSS - 当宽度为自动时,在内容更改后动画按钮宽度调整大小
- python - numpy结构化数组中的子数组不是c连续的
- ios - ios 中的 Twilio QuickStarter 项目问题