簡體   English   中英

反應鈎子狀態不更新

[英]React hook state not updating

我正在創建一個 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對象中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的狀態。

我面臨的問題是,當狀態增加時,我在 inputFields 的第一個對象中undefined required 現在是true

有了這個,我希望我的按鈕會被禁用,但我的按鈕仍然處於活動狀態,我的 mainButton 狀態沒有設置為true而是它仍然undefined有人可以幫我弄清楚我應該如何在這里更改mainButtonState嗎?

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)

你在初始化和更新變量之間混淆了。

所以這是發生的事情:

在第一次渲染你:

  • index初始化為0
  • currentComponent設置為inputFields[0]
  • mainButtonState初始化為undefined (因為currentComponent.requiredundefined

當您觸發onPress事件時,您會增加index ,這會導致第二次重新渲染。

在第二次重新渲染時:

  • currentComponent設置為inputFields[1]

就是這樣。

是的, currentComponent.required現在是true ,但這與mainButtonState的值mainButtonState

初始化僅在第一次渲染時發生,因此您的mainButtonState值保持為undefined

要設置mainButtonState ,您需要調用setButtonState 我還會將 setter 函數名稱更改為setMainButtonState以匹配變量名稱,因為將 setter 函數命名為與變量不同的名稱是不好的做法。 Setter 函數應該是它們設置的變量的名稱,以“set”為前綴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM