简体   繁体   English

State 仅在第二次渲染时设置(react-native)

[英]State only set on second render (react-native)

I'm pulling data from a Realm file db, but data seem to only appear on 2nd render.我正在从 Realm 文件 db 中提取数据,但数据似乎只出现在第二次渲染中。 Here's my code:这是我的代码:

import React, { useState, useEffect } from 'react'
import {getAllArchive} from '../Schemas/activitiesArchiveSchema';

const Stats = () => {
  const [Archives, setArchives] = useState();

  useEffect(() => {
    (async () => setArchives(await getAllArchive()))();
    console.log(JSON.stringify(Archives))
  }, []);

DB function:数据库 function:

export const getAllArchive = () => {
    return new Promise((resolve, reject) => {
        Realm.open(databaseOptions).then(realm => {
            let activitiesList = realm.objects(ARCHIVE_LIST_SCHEMA)
            resolve(activitiesList)
        }).catch((error) => reject(error))
    })
}

Output: Output:

 LOG  undefined
 LOG  {"0":{"title":"sw2","records":{"0":{"date":"4/28/2021","seconds":7,"minutes":0,"hours":1},"1":{"date":"4/27/2021","seconds":7,"minutes":0,"hours":0},"2":{"date":"4/28/2021","seconds":7,"minutes":0,"hours":0}}},"1":{"title":"jj","records":{"0":{"date":"4/25/2021","seconds":0,"minutes":55,"hours":1}}},"2":{"title":"l,kl","records":{"0":{"date":"4/28/2021","seconds":4,"minutes":12,"hours":1}}},"3":{"title":"fsdfdsf","records":{"0":{"date":"4/25/2021","seconds":4,"minutes":43,"hours":1}}},"4":{"title":"sideProj","records":{"0":{"date":"4/26/2021","seconds":30,"minutes":29,"hours":1},"1":{"date":"4/27/2021","seconds":15,"minutes":18,"hours":1}}},"5":{"title":"work","records":{"0":{"date":"4/28/2021","seconds":36,"minutes":13,"hours":0},"1":{"date":"4/28/2021","seconds":37,"minutes":11,"hours":3}}},"6":{"title":"plp","records":{"0":{"date":"4/25/2021","seconds":2,"minutes":12,"hours":3}}},"7":{"title":"fff","records":{"0":{"date":"4/25/2021","seconds":3,"minutes":10,"hours":2}}},"8":{"title":"Work","records":{"0":{"date":"4/27/2021","seconds":1,"minutes":0,"hours":0}}},"9":{"title":"chilling","records":{"0":{"date":"4/27/2021","seconds":40,"minutes":4,"hours":3},"1":{"date":"4/27/2021","seconds":0,"minutes":0,"hours":0}}}}

Can someone point out any issues in the code plz?有人可以指出代码中的任何问题吗? thx谢谢

This is not a surprise that your data is not loaded in the very first render of the component.这并不奇怪,您的数据没有在组件的第一次渲染中加载。 First, let's see what useEffect does if you don't provide any dependency- it executes on every re-render.首先,让我们看看如果你不提供任何依赖, useEffect会做什么——它在每次重新渲染时执行。

on this line of code:在这行代码上:

(async () => setArchives(await getAllArchive()))();

you're fetching data that is asynchronous, the execution will not pause here.您正在获取异步数据,执行不会在这里暂停。 so, console.log(JSON.stringify(Archives)) will be executed.因此, console.log(JSON.stringify(Archives))将被执行。 If Archived is still undefined (meaning data fetching is incomplete) you see LOG undefined .如果Archived仍然undefined (意味着数据获取不完整),您会看到LOG undefined When, the asynchronous data fetching is completed and state updated what causes the component rerender hence useEffect is called again and you see何时,异步数据获取完成并且 state 更新了导致组件重新渲染的原因,因此再次调用useEffect ,您会看到

LOG  {"0":{"title":"sw2","records":{"0":{"date":"4/28/2021","seconds":7,"minutes":0,"hours":1},"1":{"date":"4/27/2021","seconds":7,"minutes":0,"hours":0},"2":{"date":"4/28/2021","seconds":7,"minutes":0,"hours":0}}},"1":{"title":"jj","records":{"0":{"date":"4/25/2021","seconds":0,"minutes":55,"hours":1}}},"2":{"title":"l,kl","records":{"0":{"date":"4/28/2021","seconds":4,"minutes":12,"hours":1}}},"3":{"title":"fsdfdsf","records":{"0":{"date":"4/25/2021","seconds":4,"minutes":43,"hours":1}}},"4":{"title":"sideProj","records":{"0":{"date":"4/26/2021","seconds":30,"minutes":29,"hours":1},"1":{"date":"4/27/2021","seconds":15,"minutes":18,"hours":1}}},"5":{"title":"work","records":{"0":{"date":"4/28/2021","seconds":36,"minutes":13,"hours":0},"1":{"date":"4/28/2021","seconds":37,"minutes":11,"hours":3}}},"6":{"title":"plp","records":{"0":{"date":"4/25/2021","seconds":2,"minutes":12,"hours":3}}},"7":{"title":"fff","records":{"0":{"date":"4/25/2021","seconds":3,"minutes":10,"hours":2}}},"8":{"title":"Work","records":{"0":{"date":"4/27/2021","seconds":1,"minutes":0,"hours":0}}},"9":{"title":"chilling","records":{"0":{"date":"4/27/2021","seconds":40,"minutes":4,"hours":3},"1":{"date":"4/27/2021","seconds":0,"minutes":0,"hours":0}}}}

Isn't it just that your console.log is happening before setArchives?不就是你的console.log 发生在setArchives 之前吗? Try to force your log to wait for the async return to test it out.尝试强制您的日志等待异步返回以对其进行测试。

im pretty sure you cannot async setState here:我很确定你不能在这里异步 setState:

(async () => setArchives(await getAllArchive()))(); setState is not an async api, is it? setState 不是异步 api,是吗? try:尝试:

useEffect(() => {
  (async () => {
    const data = await getAllArchive();// async fetch data and store it in variable

    console.log(JSON.stringify(data, null, 2)); //log your response

    if(data){

      setArchives(data) //if success, then set state

    }else{
      console.log('could not fetch data') //if fail, resolve error somehow
    }
  }
  )();
  
}, []);

I'm new to react so I was expecting my code to wait and update state on first render.我是新手,所以我期待我的代码在第一次渲染时等待并更新 state。 However, its expected not to have value on first render and the way to deal with it, is to basically, run the dependent code in another useEffect hook that has that state in its dependencies array.然而,它预计在第一次渲染和处理它的方法上没有价值,基本上是在另一个 useEffect 钩子中运行依赖代码,该钩子在其依赖项数组中有 state。 Here's the code:这是代码:

import React, { useState, useEffect } from 'react'
import {getAllArchive} from '../Schemas/activitiesArchiveSchema';

const Stats = () => {
  const [Archives, setArchives] = useState();

  useEffect(() => {
    (async () => setArchives(await getAllArchive()))();
  }, []);

  useEffect(() => {
    // "dependent code"
    console.log(JSON.stringify(Archives))
  }, [Archives])

and obviously the first render is undefined but the second should have the value change.显然第一个渲染是未定义的,但第二个应该有值变化。

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM