简体   繁体   English

我的 useState 有问题吗? 我觉得我的 Array ReactNative 中的值并没有正确

[英]Is there an issue with my useState? I feel the values are not truing up right in my Array ReactNative

Been so curious about my console.log output.对我的 console.log output 非常好奇。

I have a button, when clicked it should basically add 1 to the use-State( 1 ) I have created but it seems that I am doing something wrong;我有一个按钮,当单击它时,它基本上应该将 1 添加到我创建的 use-State( 1 ) 但似乎我做错了什么; Please I need help with know if I am managing my State correctly {I am using React HOOKs}请帮助我了解我是否正确管理我的 State {我正在使用 React HOOKs}

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>

Once 'ADD Button' is pressed it does not start from 2 as I have 1 set as initialState.一旦按下“添加按钮”,它就不会从 2 开始,因为我将 1 设置为初始状态。 Below is my Terminal Output after clicking or Pressing 'Add Button' 3 Times以下是我的终端 Output 单击或按“添加按钮”3 次后

这是我得到的状态数组我认为在单击按钮 3 次后它是错误的

第一步设置为 1 但 2,3,4 是单击按钮时

Thank you for taking the time to look into this.感谢您抽出宝贵时间对此进行调查。 I really hoped I explained this as best as I can.我真的希望我能尽可能地解释这一点。 Thank you again!再次感谢你!

First, have a consistent data type in your state so that is will easy mapping over values to create components.首先,在 state 中具有一致的数据类型,以便轻松映射值以创建组件。

const [procedureCounter, setProcedureCounter] = useState([{
  id: 1,
  value: 1
}]);

The reason you are getting undefined is you are not accessing the array properly.您未定义的原因是您没有正确访问数组。 Check the below snippet to see how to use it.检查以下代码段以了解如何使用它。 I have also updated the map iteration for component creation.我还更新了用于创建组件的 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM