更新状态不会触发 React Native 中的重新渲染

发布于 2025-01-10 19:23:44 字数 2155 浏览 0 评论 0原文

经过整整一周的谷歌搜索和反复试验,我仍然没有弄清楚我做错了什么。

我正在用数据(对象数组)从 axios 调用填充 AsyncStorage。然后使用 useEffect 从 AsyncStorage 中的数据更新状态。所有这些都有效并且状态得到更新,但它不会触发渲染。

没有错误消息。 allData 状态已更新,但由于某种原因它不会触发重新渲染。

这就是状态:

const [allData, setAllData] = useState([
{
  fecha_inicial: toggleSwitch.startDate,
  fecha_final: toggleSwitch.endDate,
  id_emp: 0,
  nombre_emp: '',
  ventas: {
    vta_tuno_open: '0',
    vta_dia_1: '0',
    vta_sem_0: '0',
    vta_sem_1: '0',
    vta_mes_0: '0',
    vta_mes_1: '0',
    vta_anio_0: '0',
  },
  metas: {
    dia: '0',
    semana: '0',
    mes: '0',
    año: '0',
    dia_anterior: '0',
    semana_anterior: '0',
    mes_anterior: '0',
    año_anterior: '0',
  },
},

])

这是从 API 获取数据并将其保存到 AsyncStorage 中的 useEffect:

useEffect( () => {
    const interval = setInterval( async () => {
      const empresas = await fetchAll(
        idUsuario,
        toggleSwitch.startDate,
        toggleSwitch.endDate,
      )

      storeData(empresas)
    }, 15000 )
    return () => clearInterval( interval )
  }, [] )

这是从 AsyncStorage 更新 allData 状态的 useEffect。

  useEffect( async () => {
    const interval = setInterval( async () => {
        const dataFromAsyncStorage = await getData()
        const newData = dataFromAsyncStorage
        setAllData( newData )
        setIsLoading(false)
    }, 30000 )

    return () => clearInterval(interval)
  }, [] )

这是应该更新的渲染,然后“allData”状态发生变化。

return (
        <View>
          {
            allData.map((data, index) => {
              return (
                <GaugeBar
                  key={index}
                  idEmpresa={data.id_emp}
                  title={data.nombre_emp}
                  currentValue={data.ventas.vta_tuno_open.replace(/,/g, '.')}
                  limitValue={data.metas.dia.replace(/,/g, '.')}
                  height={42}
                />
              )
            }) //END-MAP
          }
        </View>
      )

我不需要更新状态 allData 数组内每个对象的属性的单独值,因为无法知道哪些值将被更新。所以我不介意每次都更新整个内容。

It's been a whole week of googling and of trial and error and I haven't still figured out what I am doing wrong.

I'm filling an AsyncStorage from an axios call with data (array of objects). Then using useEffect to update a state from the data in AsyncStorage. All of this works and the state gets updated but it doesn't trigger a render.

There are no error messages. The allData State gets updated but for some reason it doesn't trigger a re-render.

This is the state:

const [allData, setAllData] = useState([
{
  fecha_inicial: toggleSwitch.startDate,
  fecha_final: toggleSwitch.endDate,
  id_emp: 0,
  nombre_emp: '',
  ventas: {
    vta_tuno_open: '0',
    vta_dia_1: '0',
    vta_sem_0: '0',
    vta_sem_1: '0',
    vta_mes_0: '0',
    vta_mes_1: '0',
    vta_anio_0: '0',
  },
  metas: {
    dia: '0',
    semana: '0',
    mes: '0',
    año: '0',
    dia_anterior: '0',
    semana_anterior: '0',
    mes_anterior: '0',
    año_anterior: '0',
  },
},

])

This is the useEffect that fetches the data from an API and saves them into AsyncStorage:

useEffect( () => {
    const interval = setInterval( async () => {
      const empresas = await fetchAll(
        idUsuario,
        toggleSwitch.startDate,
        toggleSwitch.endDate,
      )

      storeData(empresas)
    }, 15000 )
    return () => clearInterval( interval )
  }, [] )

And this is the useEffect that updates the allData state from AsyncStorage.

  useEffect( async () => {
    const interval = setInterval( async () => {
        const dataFromAsyncStorage = await getData()
        const newData = dataFromAsyncStorage
        setAllData( newData )
        setIsLoading(false)
    }, 30000 )

    return () => clearInterval(interval)
  }, [] )

This is the render that is supposed to be updated then the "allData" state changes.

return (
        <View>
          {
            allData.map((data, index) => {
              return (
                <GaugeBar
                  key={index}
                  idEmpresa={data.id_emp}
                  title={data.nombre_emp}
                  currentValue={data.ventas.vta_tuno_open.replace(/,/g, '.')}
                  limitValue={data.metas.dia.replace(/,/g, '.')}
                  height={42}
                />
              )
            }) //END-MAP
          }
        </View>
      )

I don't need to update individual values of properties of every object inside the array of the state allData because there's no way to know which values are going to get updated. So I don't mind updating the whole thing every time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔戏命师 2025-01-17 19:23:44

问题是您没有将任何内容传递给 useEffect 的第二个参数(空数组)。 文档如果你想运行一个效果并清理它只有一次(在挂载和卸载时),您可以传递一个空数组 ([]) 作为第二个参数。这告诉 React 你的效果不依赖于 props 或 state 的任何值,因此它永远不需要重新运行。。您需要传递因变量,例如 newData

The thing is that you are not passing anything to the second argument of useEffect (empty array). The documentation says that If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.. You need to pass dependent variables e.g. newData

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文