【问题标题】:react native : what is the way to change the class component to a function component and hooks?react native:将类组件更改为功能组件和挂钩的方法是什么?
【发布时间】:2020-10-01 07:46:51
【问题描述】:

类组件变成函数组件的方法是什么? 在我的示例中,我有类组件,我尝试将其更改为功能组件和挂钩。 我该怎么做? 更改有点混乱和不清楚,所以我无法做到,我很高兴看到如何进行这样的更改

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 />;
  }
}

【问题讨论】:

  • 请查看本教程,您可能会发现它有帮助nimblewebdeveloper.com/blog/…
  • 我试了一下,也有一些错误,你能帮我转换一下吗?
  • 你尝试过什么(在这里分享尝试有问题​​)以及错误是什么(再次更新和分享有问题)?
  • 我在我的代码中制作沙拉,同时尝试将其更改为函数组件,因此我无法分享它,因为那里的一切都做得不好。

标签: javascript reactjs react-native react-hooks


【解决方案1】:

尝试按照这些步骤操作。

  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}
    />
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2022-11-30
    • 2020-12-21
    • 2020-01-29
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    相关资源
    最近更新 更多