React-Native:useState 更新数组内的对象

奥利维尔

我有一个项目列表,当单击一个项目时,它会导航到一个显示选项列表的模式。我试图增加每个选项内的计数器,它按预期工作但是当我退出模式屏幕并返回它时,选项计数器不会重置。

const myOptions = [
  { id: '001', name: 'option 001', counter: 0 },
  { id: '002', name: 'option 002', counter: 0 },
];

function ModalScreen({ route, navigation }) {
  const [options, setOptions] = useState(myOptions);

  let tempArr = [...myOptions]; 
  // Array where I increment the counter, before passing it to setOptions(tempArr)

  useEffect(() => {
    return () => {
      // because of let tempArr = [...myOptions]; changes in tempArr are copied 
      in myOptions. I want to reset myOptions when I exit the component
      console.log(options); 
      console.log(myOptions) // both output are identical
    };
  }, []);
  return (
    <View>
      <Text style={{ fontWeight: 'bold', marginBottom: 15 }}>
        Click on an option to increment counter by 1
      </Text>
      <FlatList
        keyExtractor={item => item.name}
        extraData={tempArr}
        data={options}
        renderItem={({ item, index }) => (
          <TouchableOpacity
            onPress={() => {
              tempArr[index].counter++;
              setOptions(tempArr);
            }}>
            <Text>
              {item.name} - counter: {item.counter}
            </Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
}

我在这里做了一个演示:https : //snack.expo.io/@oliviermtl/carefree-marshmallows

我花了一整天的时间试图弄清楚这个......如果需要更多解释,请告诉我谢谢

戈斯库拉·贾亚查德拉

改变

  useEffect(() => {
        return () => {
          console.log(options); 
          console.log(myOptions)
        };
      }, []);

 useEffect(() => {
    return () => {
      myOptions[0].quantity = 0;
      myOptions[1].quantity = 0;
    };
  },[]);

我所做的是将数量值更改为 0,无论何时用户关闭或从模态中退出。希望这可以帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Native:更新对象内的数组

React Native:实时更新 useState

React Native useState Hook 不会立即更新

在 useState() 之后 React Native 不会更新 UI

React Native:useState 未正确更新

更新 React useState 中的对象数组

更新 map Function React 或 React-Hooks 或 React-Native 内的数组中的对象

React Native - React Hooks - useState 不会立即更新我的状态

尝试在 React Native 中更新数组对象

在 React-Native 中,useState 不在屏幕上更新

React Native - useState 設置數據更新晚

在React Native useState中初始化数组

在 React 中使用 UseState 更新数组中的所有对象

在React中使用useState更新多个数组对象值

如何在React Native中使用其索引在useState中更新数组

React useState()-如何更新对象

在 React Native 中使用 useState

React上下文API和useState挂钩中的React Native更新状态

更新存储数组中对象的属性-React Native

Redux 更新数组中的对象(React-Native)

React Native-更新数组中对象的属性

在 React JS useState 中再次更新相同状态时,如何保持对象值的更新状态数组?

比较两个不同的数组并使用 React 中的 useState 更新对象数组

如何在不使用useState更改React native中位置的情况下更新数组元素的值?

在 React Native 中无限重复使用 useState 更新 FlatList 数据

React useState Hook-更新对象的状态

react中的useState不更新状态对象

使用useState在React中更新对象的属性

在 React 中使用 useState 挂钩更新对象