反应钩子状态不更新

安妮123

我正在创建一个 React 组件(子组件),它将 JSON/Object 数组作为输入(来自父级)作为道具。

Json 看起来像这样

const inputFields = [
  {
    key: 'name', 
    type: 'text', 
    label: `Your Full Name`,
    helper: 'Using your real name would make it more likely for you to get a match',
    templateOptions: { 
      placeHolder: 'Frank Murphy',
      templateStyle: styles.textStyle // refer to the style component
    }
  }, 
  {
    key: 'dob', 
    type: 'dateTyper', //change this to Dob component
    label: 'Your Date of birth',
    helper: 'Your Birthdate will help us in connecting you with people of similar age',
    required: true
  }]

在我的子组件中,我正在渲染它。在这个对象数组中注意第二个对象中需要的键required: true

现在,在我的子组件中,我有 touchableOpacity,我根据此状态启用/禁用它。所以这是我的子组件的粗略结构。

export const Component = (props) => {
  const { inputFields } = props
  const [index, setIndex] = useState(0)
  const currentComponent = inputFields[index]
  const {key, type, label, helper, buttonText, validator, required} = currentComponent
  console.log(required) // This is changing 
  const [mainButtonState, setButtonState] = useState(required)

然后可触摸组件的 JSX 看起来像这样

 <TouchableOpacity 
   onPress={getValueFromState}
    disabled={mainButtonState}
    > 
    <Text> {usedButtonText} </Text> 
  </TouchableOpacity>

这里 onPress 只会增加index.

我面临的问题是,当状态增加时,我undefined在 inputFields 的第一个对象中的required现在是true.

有了这个,我希望我的按钮会被禁用,但我的按钮仍然处于活动状态并且我的 mainButton 状态没有设置为true而是仍然是undefined有人可以帮助我弄清楚我应该如何更改mainButtonState这里吗?

J玛德莱娜
const [index, setIndex] = useState(0)
const currentComponent = inputFields[index]
const {key, type, label, helper, buttonText, validator, required} = currentComponent
console.log(required) // This is changing 
const [mainButtonState, setButtonState] = useState(required)

你在初始化和更新变量之间混淆了。

所以这是发生的事情:

在第一次渲染你:

  • 初始化index0.
  • 设置currentComponentinputFields[0]
  • 初始化mainButtonStateundefined(因为currentComponent.requiredundefined

当您触发onPress事件时,您会增加index,这会导致第二次重新渲染。

在第二次重新渲染时:

  • 设置currentComponentinputFields[1]

就是这样。

是的,currentComponent.required是 now true,但这与 的值无关mainButtonState

初始化仅在第一次渲染时发生,因此您的mainButtonState值仍然是undefined

要设置mainButtonState,您需要调用setButtonState. 我还将更改 setter 函数名称以setMainButtonState匹配变量名称,因为将 setter 函数命名为与变量不同的名称是不好的做法。Setter 函数应该是它们设置的变量的名称,前缀为“set”。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章