有什么方法可以使用useNavigation钩子导航到类组件吗?

时间:2020-09-06 07:10:06

标签: javascript reactjs react-native react-hooks react-navigation

是否可以使用useNavigation钩子导航到类组件?

这是我的课程:

export default class AzureLogin extends React.Component

所以我需要从AzureLogin导航到Screen1。 怎么做?

import { useNavigation } from '@react-navigation/native';

const Screen1 = (props) => {
  const [data, setData] = useState('');
  const [isLoaded, setIsLoaded] = useState(false);
  const dispatch = useDispatch();
  const userState = useSelector((state) => state.userReducer);

  const [isSync, setIsSync] = useState(false);
  const syncData = useGetUserDevicesData(isSync);
  useEffect(() => {
    if (syncData.isLoaded === true) {
      setIsSync(false);
      setData(syncData.data);
    }
  }, [syncData.isLoaded]);

  useEffect(() => {
    const getItem = async () => {
      const azureToken = await AsyncStorage.getItem('AZURE-TOKEN');
      const userName = await AsyncStorage.getItem('AZURE-USERNAME');
      const googlToken = await AsyncStorage.getItem('GOOGLE-TOKEN');
      const deviceId = await AsyncStorage.getItem('DEVICE-ID');
      const platformId = await AsyncStorage.getItem('PLATFORM-TYPE');

      getSaveUserTokenData({
        userName,
        googlToken,
        platformId,
        deviceId,
        azureToken,
      });
    };
    getItem();
  }, []);

  const getSaveUserTokenData = async (data) => {
const navigation = useNavigation();

    const url =
      'https://' +
      'userName=' +
      data.userName +
      '&userToken=' +
      data.googlToken +
      '&PlatformType=' +
      data.platformId +
      '&DeviceID=' +
      data.deviceId;
    await fetch(url, {
      method: 'GET',
      headers: {
        Authorization: data.azureToken,
      },
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(
          'THE FETCH DATA TO getSaveUserTokenData FUNCTION IS:',

          data
        );
      })
      .catch((error) => {}); //**HERE I NEED TO NAVIGATE !!**
  };

1 个答案:

答案 0 :(得分:1)

能否浏览屏幕并不取决于它是功能组件还是类组件。因此,您当然可以导航到AzureLogin。

但是正如#1 Rules of Hooks明确指出的那样

仅位于顶层的呼叫挂钩

请勿在循环,条件或嵌套函数中调用Hook。 相反,请始终在React函数的顶层使用Hook。通过 遵循此规则,请确保在相同的位置调用Hook 每次渲染组件时都要订购。这就是让React能够 正确保留多个useState与之间的Hook的状态 useEffect调用。 (如果您有好奇心,我们将对此进行深入说明

因此,根据您的Screen1组件,

您应该将useNavigation钩子从getSaveUserTokenData移到顶层,如下所示:

const Screen1 = (props) => {
  const [data, setData] = useState('');
  const [isLoaded, setIsLoaded] = useState(false);
  const dispatch = useDispatch();
  const userState = useSelector((state) => state.userReducer);
  const navigation = useNavigation();
  ...

然后,您才可以在任何需要的地方拨打navigation.navigate('AzureLogin')