【问题标题】:Weird situation where useState works sometimes and it does not works sometimesuseState 有时有效但有时无效的奇怪情况
【发布时间】:2019-12-31 08:23:24
【问题描述】:

我在 react native 中使用钩子,setState 有时有效,有时无效。我分享的代码是在到达平面列表末尾时增加计数。我为 count 添加的钩子会打印增量值,但是当我在某处使用它时,它总是使用 10。

import React, { useState, useEffect } from 'react';

export default Trending = (props) => {

   const [count, setCount] = useState(10);

   function showMore() {
        setLoading(true);
        setCount(count + 10);
        getRecentlyAdded();
    }

    async function getRecentlyAdded() {
      try {
        console.log(count); //always prints 10
      } catch (e) {
        setLoading(false);
      }
    }

       <FlatList
                data={dataList}
                renderItem={({ item }) => <SwipeList goToDetailed={goToDetailedPageClick} item={item} />}
                keyExtractor={item => item.id}
                initialNumToRender={10}
                onEndReachedThreshold={0.3}
                onEndReached={() => {
                    showMore();
                }}
            />

}

它总是在控制台中打印 10 并且值永远不会更新。

我添加了一个钩子来检查计数值

useEffect(() => {
        console.log(count); //prints incremented but still uses 10
    }, [count])

【问题讨论】:

  • 我认为您不能依赖该值,因为它来自关闭。如果您将 console.log 移出 showMore 函数会怎样,所以每次渲染都会调用它? setState 将使用新状态触发重新渲染。
  • FlatList 不使用计数...

标签: javascript reactjs react-native react-hooks


【解决方案1】:

如果状态值保持不变,则setStateuseState 将不会更新或呈现。希望这能给你一点提示。

【讨论】:

  • 嗨 Nikhil,计数增加了,所以我不认为状态保持不变是这里的问题。这个人问为什么状态 change 没有反映在它被使用的地方。这意味着发生了变化。
  • 您好对不起,实际上您需要使用回调来立即反映状态更改,因为状态更新可能需要一些时间。您可以在组件中使用 useEffect() 挂钩并解决我的用例。
猜你喜欢
  • 2020-09-11
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 2012-08-02
  • 2015-03-31
  • 1970-01-01
相关资源
最近更新 更多