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

eri*_*hio 1 reactjs react-native react-navigation react-hooks

我正在使用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', () => {
      console.log('focus');
      console.log(this.state.text); // this is null only in the first focus
    });
  }

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

我在第一个版本中做错了什么吗?

eri*_*hio 7

好的,我找到了使用 useRef 钩子的解决方案: React useState hook event handler using initial state

所以就我而言应该是:

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

function TextScreen({navigation}) {
  const [text, _setText] = useState(null);
  const textRef = useRef(text);
  const setText = newText => {
    textRef.current = newText;
    _setText(newText);
  };

  useEffect(() => {
    setText('Some text.');
    navigation.addListener('focus', () => {
      console.log('focus');
      console.log(textRef.current);
    });
  }, []);

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