我在组件中有以下代码:我无法获得更新的状态。
当我调用 createUserList 时,我可以在 UserList 组件中看到用户,但在 UserComponet 中,当我登录用户时,我看不到那里的用户。
但是我可以在 react 开发工具中看到更新的状态
我使用的代码:
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>
)
}
答案 0 :(得分:1)
您可以为此使用 useEffect 并将状态作为依赖项传递,因此每次用户状态发生更改时,它都会被调用。
useEffect(() => {
console.log(users);
}, [users])
答案 1 :(得分:0)
useEffect
应该可以达到您的目的。
useEffect(() => {
console.log(users)
},[users]);
上述函数(在本例中,其控制台日志记录“users”)仅在其(用户)状态更改或更新时执行。考虑将 setTimeOut
替换为 useEffect
。
答案 2 :(得分:0)
使用 useEffect
钩子:
useEffect(() => console.log(users), [users])
完整代码:
function UserComponent() {
const [users, setUsers] = useState<any>([])
useEffect(() => console.log(users), [users])
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)
}
return (
<UserList users={users}/>
)