reactjs - 可以useEffect等待setState(hook)吗?
问题描述
我在 useEffect 中有一个代码(如 componentDidMount):
useEffect(()=>{
const idChat = props.match.params.id;
const data = {
idChat,
user: props.user._id
}
authService.getChat(data)
.then(res =>{
const userChat = res.data.users.filter(e=> e!== data.user).toString()
authService.getuser(userChat)
.then(res=>{
setOtherUser(res.data)
})
})
.catch(err=>{
setErrors(err.response)
})
}, [])
此代码运行一次。好的。
我需要另一个使用otherUser
状态的 useEffect。但它还没有设置。
useEffect(()=>{
socket.readUsers(users => {
const is = users.users.indexOf(otherUser._id);
console.log(users,otherUser._id, is)
if(is < 0){
setUsersStatus(false)
}else{
setUsersStatus(true)
}
});
})
如果我有条件,永远不要进入 if :/ 我如何在 useEffect 中调用 otherUser?
解决方案
将其添加为效果的依赖项。然后,您可以在otherUser
未设置时跳过执行代码。
useEffect(() => {
if (otherUser) {
socket.readUsers(users => {
const is = users.users.indexOf(otherUser._id);
console.log(users, otherUser._id, is);
if (is < 0) {
setUsersStatus(false);
} else {
setUsersStatus(true);
}
});
}
}, [otherUser]);
推荐阅读
- python - 可以使用自己的 django admin
- python - Django 消息:如何更改 html 中的消息文本?
- java - 删除相同的值但保留附加值
- wordpress - 如何在 Visual Portfolio 中添加视频?
- solr - 尝试在 SOLR 上使用“bf”时出错“类型不匹配:时间戳被索引为 SORTED_NUMERIC”
- python - 打包具有多处理代码的 python 模块
- ruby - 如何删除数组中重复的连续元素?
- reactjs - Reactjs 组件 - 一对多
- ios - 在 SwiftUI 中传递视图或高阶组件
- ruby - 如何定义一个名称以问号结尾并且可以访问外部方法变量的内部方法?