簡體   English   中英

react native:將類組件更改為函數組件和鈎子的方法是什么?

[英]react native : what is the way to change the class component to a function component and hooks?

將類組件更改為功能組件的方法是什么? 在我的示例中,我有類組件,我嘗試將其更改為函數組件和鈎子。 我該怎么做? 更改有點混亂和不清楚,所以我無法做到,我很高興看到這樣的更改是如何進行的

export default class AzureLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      azureLoginObject: {},
      loginSuccess: false,
      loading: true,
    };
    this.azureInstance = new AzureInstance(credentials);
    this._onLoginSuccess = this._onLoginSuccess.bind(this);
  }

  async componentDidMount() {
    const firstTime = await AsyncStorage.getItem('AZURE-TOKEN');
    if (firstTime != null) {
      this.props.navigation.dispatch(StackActions.replace('דגימות איכות מים'));
    } else {
      this.setState({ loginSuccess: firstTime != null, loading: false });
    }
  }

  _onLoginSuccess() {
    this.azureInstance
      .getUserInfo()
      .then(async (result) => {
        console.log(result);
        //HERE EXAMPLE FOR STORE SOME VARIABLE INTO MY REDUX STORE
        store.dispatch(userPrincipalName(result.userPrincipalName));
        store.dispatch(givenName(result.mobilePhone));
        ///THIS IS AZURE TOKEN
        // console.log('AZURE-TOKEN', JSON.stringify(this.azureInstance.token));

        ///SAVE AZURE-TOKEN INTO AsyncStorage
        await AsyncStorage.setItem(
          'AZURE-TOKEN',
          JSON.stringify(this.azureInstance.token)
        );
        ///SAVE AZURE-USERNAME INTO AsyncStorage
        await AsyncStorage.setItem(
          'AZURE-USERNAME',
          result.userPrincipalName.split('@')[0]
        );

        this.setState({
          loginSuccess: true,
          azureLoginObject: result,
        });
        this.props.navigation.dispatch(
          StackActions.replace('דגימות איכות מים')
        );
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.loading)
      return (
        <AzureLoginView
          azureInstance={this.azureInstance}
          loadingMessage="Requesting access token"
          onSuccess={this._onLoginSuccess}
        />
      );
    return <ActivityIndicator />;
  }
}

嘗試按照以下步驟操作。

  1. 將狀態轉換為useState反應鈎子。 您還可以使用函數初始值設定項將新的 AzureInstance 保存在狀態中。 可以使用參考。
  2. 使用空依賴數組將componentDidMount轉換為useEffect 創建內部異步函數並調用。
  3. this所有引用轉換為新的無實例引用(主要是從所有內容中刪除this )。
  4. 解構函數簽名中傳遞的道具

以下應該讓你接近。

代碼:

const AzureLogin = ({ navigation }) => {
  const [azureInstance] = useState(() => new AzureInstance(credentials));
  const [azureLoginObject, setAzureLoginObject] = useState({});
  const [loginSuccess, setLoginSuccess] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadData = async () => {
      const firstTime = await AsyncStorage.getItem('AZURE-TOKEN');

      if (firstTime) {
        navigation.dispatch(StackActions.replace('דגימות איכות מים'));
      } else {
        setLoginSuccess(firsTime !== null);
        setLoading(false);
      }
    };

    loadData();
  }, []);

  const _onLoginSuccess = () => {
    azureInstance
      .getUserInfo()
      .then(async (result) => {
        console.log(result);
        //HERE EXAMPLE FOR STORE SOME VARIABLE INTO MY REDUX STORE
        store.dispatch(userPrincipalName(result.userPrincipalName));
        store.dispatch(givenName(result.mobilePhone));
        ///THIS IS AZURE TOKEN
        // console.log('AZURE-TOKEN', JSON.stringify(azureInstance.token));

        ///SAVE AZURE-TOKEN INTO AsyncStorage
        await AsyncStorage.setItem(
          'AZURE-TOKEN',
          JSON.stringify(azureInstance.token)
        );
        ///SAVE AZURE-USERNAME INTO AsyncStorage
        await AsyncStorage.setItem(
          'AZURE-USERNAME',
          result.userPrincipalName.split('@')[0]
        );

        setLoginSuccess(true);
        setAzureLoginObject(result);

        navigation.dispatch(
          StackActions.replace('דגימות איכות מים')
        );
      })
      .catch((err) => {
        console.log(err);
      });
  }

  return loading ? (
    <ActivityIndicator />
  ) : (
    <AzureLoginView
      azureInstance={azureInstance}
      loadingMessage="Requesting access token"
      onSuccess={_onLoginSuccess}
    />
  );
}

暫無
暫無

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

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