首页 > 解决方案 > 可以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?

标签: reactjs

解决方案


将其添加为效果的依赖项。然后,您可以在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]);

推荐阅读