【发布时间】:2021-08-29 23:20:06
【问题描述】:
我正在尝试解决这个问题,但我不能,我将状态从父组件传递给子组件,如下所示:
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,但是当我再次更改它时它返回 undefined,这是怎么回事?谢谢。
【问题讨论】:
标签: javascript reactjs react-props use-state