我怎么能得到索引从地图使用钩子?



我在我的代码中使用路由器和钩子,所以我有两个分量"AddRoom"Homescreen"在应用程序中,我有adroom()箭头函数,钩子称为"rooms"发送到adroom "组件如下:

<Router>
<Switch>
<Route exact path='/' component={() => { returnn <HomeScreen rooms={rooms} /> }} /> 
<Route exact path='/AddRoom' component={() => { return <AddRoom add={addRoom} rooms={rooms} /> }} /
</Switch>
</Router>

"addRoom"功能:

const [rooms, setRooms] = useState([]);
const addRoom = (room, name, color) => {
//I have tried to use here map to add index for array "rooms" it is not working//
setRooms([...rooms, { room: room, name: name, color: color ,index:{index}}])}

我试图得到索引每次我添加一个房间到"rooms"数组,但它不会添加到我的数组,我不明白为什么,我怎么能做到这一点?

那就是" adroom "组件:

import React, { Component, useState } from
'react'
import context from 'react- 
bootstrappp/esm/AccordionContext';
import { render } from 'react-dom';
import { useHistory } from "react-router- 
dom";
export default function AddRoom(props) {
const [room, setRoom] = useState()
const [name, setName] = useState()
const [color, setColor] = useState('black')
const [showError, setShowError] = useState(false)
const [index, setIndex] = useState([]);
const history = useHistory();

const validInput = () => {//input validation
if ((name == null) || ((room == 'Choose') || (room == null))) {//no name typed and no room chosen
debugger
window.alert('Please choose a room and enter at least one character in room name');
return true;//if alert pops up
}
else {
if (name.length > 5) {
return false;//name is too long
}
}
}
const AddClick = () => {
let result = validInput();
let path = '/';
if (result == true)//no name was typed and room was not selected
{
debugger
history.push(path);
}
else {
if (name.length > 5) {//name is too long
setShowError(true)
}
else//all fields are correct, go back to home screen with ner room
{
setShowError(false)
/*  {props.rooms.map((element, i) => { */
props.add(room , name , color /*(setIndex(...index, { index: i })) */);
}
)} 
history.push(path);
}
}




return (
<div className='container' >
<div className='row'>
<div className='col-sm-12 text-center' style={{ textAlign: 'center', position: "relative", top: "80px", }}>
<select onChange={(element) => { setRoom(element.target.value) }} name="room" id="room">
<option value="Choose">Choose your room</option>
<option value="Livingroom">Livingroom</option>
<option value="Kitchen">Kitchen</option>
<option value="Bedroom">Bedroom</option>
<option value="Bathroom">Bathroom</option>
</select>
<br /><br />
<input onChange={(element) => { setName(element.target.value) }} id="name" type="text" placeholder="Room Name"></input>
<div style={{ color: 'red', marginTop: '5', display: showError ? "block" : "none" }}>Room Name Is More Then 5 Character</div>
<br /><br />
<input onChange={(element) => { setColor(element.target.value) }} id="color" type="color" placeholder="Room Color"></input>
<br /><br />
<button onClick={AddClick}>Create Room</button>
</div></div></div>
)
}

在调用addrooom函数之前:

rooms=[{}]

调用adroom函数后:

rooms=[{room:"Kitchen",name:"Kit",color:"red",index:0},{room:"Bathroom",name:"Bat",color:"green",index:1}...]

如果我正确理解了你的问题,你正在尝试map你的房间数组,你想要数组中每个房间的索引。

如果你想在map-ing数组时获得房间的索引,你可以向map函数提供第二个参数,它将把索引传递给它。

rooms.map((room, index) => {
// Do stuff...
});

实际上在对象中存储索引是一种反模式,因为您无法保证存储的索引实际上与数组中的索引匹配。任何时候你添加或删除一个房间,而不是在最后,你必须用它们的新索引更新所有的房间。另外,除非您在数组之外存储对所有这些房间的引用,否则无论如何都必须在访问房间之前拥有索引。

但是如果你仍然想这样做,你可以:

  1. 在添加房间时存储索引
// Room is being added at the end, so its index must be rooms.length
setRooms([...rooms, { ...room, index: rooms.length }]);
  1. 每次添加后更新索引
// This is basically the first part of my answer with extra steps
setRooms([...rooms, room].map((room, index) => ({ ...room, index: index })));

相关内容

  • 没有找到相关文章

最新更新