更新React Native中的多个状态(分别增加每个组件的计数器)



我在这个主题上发现了一些类似的问题,但它们通常是关于React的,而不是专门针对React Native的,我发现很难将它们翻译成来自Android/Java背景的全新问题。我有一个组件,它有一个加号和减号图标来增加/减少它们的计数器。然而,这个组件被使用了多次,我不想为这个组件的每个实例都有一个total和setTotal,这样每个实例都可以独立于任何其他组件更新自己的total。目前,当我点击任何加号/减号时,它们都会更新。我正在使用钩子

const [total, setTotal] = useState(0)
const increase = () => {
setTotal(total + 1)
}
const decrease = () => {
setTotal(total - 1)
}

<Reportable
title={'First'}
decrease={decrease}
increase={increase}
total={total}
onPress={handleChange}
/>
<Reportable
title={'Second'}
decrease={decrease}
increase={increase}
total={total}
/>

非常感谢。

问题是您正在向两个组件传递相同的状态(合计(。所以,谁增加了它或减少了它并不重要……他们将共享这些值,因为两者都使用相同的状态。

如果每个组件都需要知道它增加了多少次,那么应该为组件本身创建一个状态,如下所示:

import React from 'react';
import { View, Button } from 'react-native';
export default function Reportable() {
const [total, setTotal] = useState(0)
const increase = () => {
setTotal(total + 1)
}
const decrease = () => {
setTotal(total - 1)
}
return (
<View>
<Button onPress={increase} >Increment</Button>
<Button onPress={decrease} >Decrement</Button>
</View>
);
}

现在在App.js中导入Reportable,如下所示:

import React from 'react';
import { View } from 'react-native';
import Reportable from './Reportable';
export default function App () {
return (
<View>
{/* This is the first Reportable */}
<Reportable />
{/* This is the second Reportable */}
<Reportable />
</View>
);
}

现在,如果您需要在App.js中获取每个计数,请向我们提供有关您试图实现的内容的更多详细信息,以便我们能够找到适合您问题的解决方案。

根据@edilsomm217的回答,这是一个对我有用的示例。

import React from 'react';
import { View, Button } from 'react-native';
export default function Reportable() {
const [total, setTotal] = useState(0)
const increase = () => {
setTotal(total + 1)
props.increase()
}
const decrease = () => {
setTotal(total - 1)
props.decrease()
}
return (
<View>
<Button onPress={increase} >Increment</Button>
<Button onPress={decrease} >Decrement</Button>
</View>
);
}

现在在App.js中导入Reportable,如下所示:

import React from 'react';
import { View } from 'react-native';
import Reportable from './Reportable';
export default function App () {
return (
<View>
{/* This is the first Reportable */}
<Reportable 
increase={increase}
decrease={decrease}
/>
{/* This is the second Reportable */}
<Reportable
increase={increase}
decrease={decrease}
/>
</View>
);
}

因此,当分别在Reportable.js文件或App.js下执行类似<Text>{total}</Text>的操作时,我既可以单独更新总数,也可以同时获得所有项目的组合金额。

最新更新