简体   繁体   中英

React Native: why are useState hooks sometimes undefined?

In my React Native app I have two components, A and B :

export const A = () => {
  const [text, setText] = useState('');
  return (
    <View>
      <B
        _text={text}
        _setText={setText}
      />
    </View>
  )
}

const B = ({_text, _setText}) => {
  console log(_text, _setText);
  ...
  ...
}

I console.log _text and _setText in B . This console.log gets called multiple times whenever I open the B component, and sometimes it logs both _text and _setText as undefined .

Does anyone know why this would be?

You're most likely rendering the B Component before the text state is updated. To fix it, check that it isn't null/empty:

export const A = () => {
  const [text, setText] = useState('');
  return (
    <View>
      {text ? <B
        _text={text}
        _setText={setText}
      /> : null}
    </View>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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