我正在尝试解决这个问题,但我做不到,我将状态从父组件传递到子组件,如下所示:
Main.js
...
const [chatRooms, setChatRooms] = useState([])
const [currentRoom, setCurrentRoom] = useState({})
const prevRoom = useRef()
useEffect(()=>{
const getRooms = async() =>{
const {data} = await axios.get('chat/rooms')
setChatRooms(data)
setCurrentRoom(data[0])
}
getRooms()
},[])
useEffect(()=>{
if (currentRoom !== prevRoom.current)
prevRoom.current = currentRoom
if (prevRoom.current?.id)
disconnect(prevRoom.current.id)
connect()
},[currentRoom])
return (
<ChatSelect rooms={chatRooms} currentRoom={currentRoom.id} setCurrentRoom={setCurrentRoom} />
)
ChatSelect.js
const ChatRoomSelection = ({rooms, currentRoom, setCurrentRoom})=>{
const handleChange = (e) =>{
setCurrentRoom(e.target.value)
//here fails and the selected value can't be set properly in the select option
console.log(currentRoom)
}
return (
<div>
<select name="rooms" value={currentRoom} onChange={(e)=>handleChange(e)}>
{
rooms.map(room=>(
<option value={room.id} key={room.id}>{room.name}</option>
))
}
</select>
</div>
)
}
当我选择另一个聊天室时,currentRoom第一次返回正确的id,但当我再次更改它时,它返回未定义,发生了什么?非常感谢。
根据我所能解析的,尽管在您的代码中,currentRoom
似乎应该是一个完整的房间对象,但在select的onChange处理程序中,您正在将其更新为房间id值。
我认为您需要传递整个房间对象作为选项的值。
<select
name="rooms"
value={currentRoom.id}
onChange={handleChange}
>
{rooms.map(room => (
<option value={room} key={room.id}>{room.name}</option>
))}
</select>
或者,您可以将currentRoom
严格保留为id
值,而不是对象。
主
...
const [currentRoom, setCurrentRoom] = useState(null);
...
useEffect(()=>{
const getRooms = async() =>{
const {data} = await axios.get('chat/rooms');
setChatRooms(data);
setCurrentRoom(data[0].id); // <-- save room id
}
getRooms();
}, []);
...
return (
<ChatSelect
rooms={chatRooms}
currentRoom={currentRoom} // <-- pass room value
setCurrentRoom={setCurrentRoom}
/>
);
ChatSelect
<select
name="rooms"
value={currentRoom}
onChange={handleChange}
>
{rooms.map(room => (
<option value={room.id} key={room.id}>{room.name}</option>
))}
</select>