【问题标题】:How to use props within UseEffect of the child component?如何在子组件的 UseEffect 中使用道具?
【发布时间】:2021-06-30 21:47:44
【问题描述】:

我希望子组件根据我通过父组件传递的道具来获取 Firebase 集合。问题是当我尝试在子组件的 UseEffect() 中获取我的道具时,它是未定义的。

我试过了

export default function Parent(){

  const [activeUser, setActiveUser] = useState();
  const [users, setUsers] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  
  const fetchUsers = async () => {
    let tempUsers = [];
    await Firebase.firestore().collection('users').get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        tempUsers.push({
          id: doc.id,
          data: doc.data(),
        })
      });
    })
    setUsers(tempUsers);      
  }

  useEffect(() => {
    fetchUsers().then(() => {
      setActiveUser(users[0]);
      setIsLoading(false);
    })
  },[]);
  
  if(isLoading){
    <View>
      <Text>Loading...</Text>
    </View>
  }else{
    return (
      <View>
        <Child user={activeUser} />
      </View>
    )
  }   
}

export default function Child(props){
      
  useEffect(() => {
        console.log(props.user)
  }, []) // I even tried something like [props | props.user] but nothing helped :/

  ...

   }

为什么我的 props.user 未定义?

【问题讨论】:

  • 子中的useEffect 只会执行一次,因为您将[] 作为第二个参数传递。由于父级异步获取用户然后将其传递给子级,因此它将错过更新的值。将[] 更改为[props.user],或者只是在你的函数体中使用props.user 应该可以解决问题。
  • 我看到你尝试过这个。你是否在父组件中放置了一个断点并验证对setActiveUser 的调用实际上正在执行(并且具有非未定义的值?)
  • 试试if (isLoading || !activeUser)

标签: javascript reactjs firebase react-native google-cloud-firestore


【解决方案1】:

很可能是因为useEffect() 是同步的,而您的fetchUser() 是异步的。您需要将fetchUsers() 调用放入useEffect() 内的闭包中以使其完成,并且您需要使user 的孩子容忍 在结果出现之前未定义. 另请注意,不能保证SetActiveUser()SetIsLoading() 的订单将适用。

【讨论】:

    【解决方案2】:

    尝试将用户添加为父函数的使用效果中的依赖项,并将props.user添加为子功能的使用效果中的依赖项。

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2019-08-21
      • 2021-01-16
      • 1970-01-01
      • 2020-04-03
      • 2021-06-06
      • 2021-02-06
      • 1970-01-01
      • 2019-12-04
      相关资源
      最近更新 更多