react-native - 状态更改时 useEffect 未运行

标签 react-native react-hooks asyncstorage

我有一个屏幕 (MyPics.js) 显示用户从另一个屏幕选择的图像集合。我从异步存储中获取选定的图像。

如果我选择图像然后重新启动模拟器,一切正常。当我导航到 MyPics.js 屏幕时,我会看到以前图像选择中存储在 AsyncStorage 中的所有图像。

  const MyPicsScreen = props => {
    const [picList, setpicList] = useState([]);

    useEffect(() => {
      console.log("I'm in!! picList data is: " +  picList);
      AsyncStorage.getItem("mypics").then((response) => {
      const currentData = JSON.parse(response);
      setpicList(currentData);
      console.log("Current picList data will be: " + currentData);
    });
   }, []);


  return (
<View style={styles.wrapper}>
  <ScrollView>
    <View style={{flexDirection: "column", justifyContent: "center", alignItems: "center"}}>

      {picList ? picList.map((item, index) => {
        return (
            <View key={index} style={styles.viewItem}>
              <Image style={{width: 200, height: 131}} source={Images[PicList[item][3]]} />
            </View>
          );
        }
      ) : <View><Text>You haven't selected any pics yet</Text></View>}

    </View>
  </ScrollView>
</View>
   );
 };

终端显示:
  I'm in!! picList data is:  //No data, as expected. Nothing is retrieved yet, then...
  Current picList data: pic001,pic007,pic099 // That shows, correctly, what's stored and screen shows those images 

但是如果我添加图像,除非我重新启动模拟器,否则新图像不会显示。另外,控制台中没有读出,所以 useEffect 没有运行以获取数据并重置状态。

我假设返回 MyPics 屏幕会导致重新渲染,但我可能错了。

我在 MyPics.js 屏幕上制作了 3 个按钮,它们在 asyncstorage 上手动运行 removeItem 或 setItem 或 getItem,然后删除或设置或获取图像,然后更新 picList 状态。

那个有效。

当我使用按钮时,它会获取或删除先前设置的图像或设置新图像,并且屏幕会重新呈现以显示状态更改。

因此,当我导航到 MyPics.js 屏幕时,useEffect 没有运行。它只在第一次渲染时运行。

当我添加 picList 状态作为依赖项时,
  }, [picList]);

它可以工作,但控制台正在无限循环中运行。

这是正常的吗?我应该忽略无限滚动的控制台还是我错过了一步?我是否应该使用焦点监听器在重新访问时重新呈现页面,因为当我返回 MyPics 屏幕时我只需要新数据。

最佳答案

在经历了很多痛苦和浪费时间之后,这有效:

 useEffect(() => {
  AsyncStorage.getItem("mypics").then((response) => {
  setpicList(JSON.parse(response);
});
}, []);

const getList = useCallback(() => {
  AsyncStorage.getItem("mypics").then((value) =>{
  setpicList(JSON.parse(value));
});
}, [picList]);

可以在此线程中找到一些非常实用的功能组件示例:

React navigation didfocus event listener works differently between class component and functional component

返回屏幕时需要进行焦点检测,以便再次运行 useEffect 函数。

关于react-native - 状态更改时 useEffect 未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252007/

相关文章:

react-native - 语法错误 : You can only use Class Properties when the 'classProperties' plugin is enabled

javascript - 使用 React useState() Hook 更新和合并状态对象

javascript - 如何在 react Hook 中更新状态的单个属性?

javascript - useReducer 返回一个 promise 而不是更新的状态

authentication - 无法从 React Native 中的 AsyncStorage 返回 token

react-native - 如何为 detox e2e 测试提供自定义测试文件路径

android - react native android的方向样式问题

react-native - 找不到模块 'react-native-elements'

javascript - 如何在 React Native 中使用 AsyncStorage multiGet 检索数据

javascript - 如何从 react-native 的异步函数中获取值(value)?