我想将其更改为挂钩格式或函数。
代码
updateRoom(roomId){
if (roomId === '') {
this.setState({RoomId: '', Room: ''})
} else {
this.setState({RoomId: roomId.key, Room: roomId.name});
}
}
三元运算符中我缺少什么?
我是否必须将函数名称更改为useUpdateRoom
才能表示钩子函数?
HOOK
function UpdateRoom(roomId) {
return '' ? setRoomId : Room
}
function App() {
const [rooms, setRooms] = useState('');
const [roomId, setRoomId] = useState('');
const [user, setUser] = useState('');
return (
<div className="app">
<div className="room">
{rooms.map((room, index) => (
<Room key={index} index={index} room={room} />
))}
</div>
</div>
)
}
答案 0 :(得分:1)
您的三元不评估roomId。为了清楚起见,我还将参数重命名为“ id”。应该是:
function App() {
const [rooms, setRooms] = useState('');
const [roomId, setRoomId] = useState('');
const [user, setUser] = useState('');
function updateRoom(id) {
return id === ''
? setRoomId('')
: setRoomId(id)
}
return (
<div className="app">
<div className="room">
{rooms.map((room, index) => (
<Room key={index} index={index} room={room} />
))}
</div>
</div>
)
}
此外,您需要将该函数放入App中,以便它可以访问setRoomId。
最后,我看不到您在哪里调用它,但这有点像:
<button onClick={() => updateRoom(some_id)}>Change Room</button>