我在组件中有以下代码: 我无法获得更新的状态。
当我调用 createUserList 时,我可以在 UserList 组件中看到用户,但在 UserComponet 中,当我登录用户时,我看不到那里的用户。
我使用的代码:
function UserComponent() {
const [users, setUsers] = useState<any>([])
const register = () => {
userAgent.delegate = {
onMessage(message: Message) {
let usernameList = message.event.entry
if (message.event['@_category'] === 'activate') {
createUserList(usernameList);
} else if (message.event['@_category'] === 'de-activate') {
// empty user list but I can see users in react dev tools
console.log(users)
const username = message.event.entry
removeUser(username)
}
}
}
}
const createUserList = (usernameList: any) => {
let userList: any = []
usernameList.forEach((user: any) => {
userList.push({'uri': user['@_uri'], 'name': user['@_uri'].substr(10, 8)})
})
// here I can see updated userList
console.log(userList)
setUsers(userList)
setTimeout(() => {
// users is empty here
console.log(users)
}, 5000)
}
return (
<UserList users={users}/>
)
}
function UserList({users}) {
return (
<div>
{users.map((user) => <h2>user</h2>)}
</div>
)
}