小编eri*_*hio的帖子

如何访问反应导航监听器中的当前状态?

我正在使用react-navigation 5 创建一个react-native 应用程序。

假设我有一个像这样的屏幕组件:

import {View, Text} from 'react-native';

function TextScreen({navigation}) {
  const [text, setText] = useState(null);

  useEffect(() => {
    setText('Some text.');
    navigation.addListener('focus', () => {
      console.log('focus');
      console.log(text); // this is always null :/
    });
  }, []);

  return (
    <View>
      <Text>{text || 'No text'}</Text>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么每个焦点都console.log(text)显示出价值。null我希望文本仅出现null在第一个焦点中,但这种情况一直在发生。

但是当我将此组件更改为类组件时,一切都按预期工作:

import {View, Text} from 'react-native';

class TextScreen extends React.Component {
  state = {
    text: null
  }

  componentDidMount() {
    this.setState({text: 'Some text'});
    this.props.navigation.addListener('focus', () => …
Run Code Online (Sandbox Code Playgroud)

reactjs react-native react-navigation react-hooks

1
推荐指数
1
解决办法
4052
查看次数