对我的 console.log 输出很好奇。
我有一个按钮,单击时它基本上应该向我创建的 use-State( 1 ) 添加 1,但似乎我做错了什么;请帮助我了解我是否正确管理我的状态{我正在使用 React HOOK}
const [procedureCounter, setProcedureCounter] = useState([1]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...ProcedureCounter,
{
id: procedureCounter.length,
//value: procedureCounter + 1 // value is undefined for some reason so I removed it but still works
},
]);
console.log(ProcedureCounter);
{ procedureCounter.map((item, value) => (
<View style={{ marginVertical: 15 }} key={item.id + 1}>
<ProcedureSteps step={value + 1} /> //This is a TexteInput Form
</View>
))}
<TouchableOpacity onPress={addProcedureHandler}>
ADD Button
</TouchableOpacity>
一旦按下“添加按钮”,它就不会从 2 开始,因为我将 1 设置为初始状态。 以下是单击或按“添加按钮”3 次后的终端输出
感谢您花时间调查此问题。我真的希望我能尽我所能地解释这一点。再次感谢您!
最佳答案
首先,在您的状态中具有一致的数据类型,以便可以轻松映射值以创建组件。
const [procedureCounter, setProcedureCounter] = useState([{
id: 1,
value: 1
}]);
您未定义的原因是您没有正确访问数组。检查下面的代码片段以了解如何使用它。我还更新了组件创建的 map 迭代。
const [procedureCounter, setProcedureCounter] = useState([{
id: 1,
value: 1
}]);
const addProcedureHandler = () => {
setProcedureCounter((procedureCounter) => [
...procedureCounter,
{
id: procedureCounter[procedureCounter.length -1].id + 1,
value: procedureCounter[procedureCounter.length -1].value + 1
},
]);
console.log(procedureCounter);
{ procedureCounter.map((item) => (
<View style={{ marginVertical: 15 }} key={item.id}>
<ProcedureSteps step={item.value} /> //This is a TexteInput Form
</View>
))}
<TouchableOpacity onPress={addProcedureHandler}>
ADD Button
</TouchableOpacity>
关于javascript - 我的 useState 有问题吗?我觉得我的 Array ReactNative 中的值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62098061/