【问题标题】:State is not updating. I want to fetch data from the firestore状态未更新。我想从 Firestore 中获取数据
【发布时间】:2020-08-31 17:17:04
【问题描述】:

我已成功从 firestore 检索数据,但无法更新我的状态。 请检查代码。

export const TaskContextProvider = (props) => {

    const [Tasks, setTasks] = useState([])

    const { User } = useContext(AuthContext)

    useEffect(() => {
        firebase.firestore()
        .collection("Users")
        .doc(User.id)
        .collection("Tasks")
        .onSnapshot((snapshot) => {
            const newtask = snapshot.docs.map((doc)=>({
                id : doc.id,
                ...doc.data()
            }))
            setTasks(newtask)
            console.log('newtask', newtask)
            console.log('Tasks', Tasks)
        })
    }, [])

下面的控制台输出是

newtask (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Tasks []

【问题讨论】:

标签: reactjs firebase google-cloud-firestore react-hooks


【解决方案1】:

setTasks 是异步的,并且在从设置其新值的同一函数中调用时可能永远不会显示正确的值。相反,将其记录在useEffect 之外,以查看它是否实际上正在更新。然后你会看到每个渲染的console.log。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多