简体   繁体   中英

call the method of another class in a hooks

hi everyone i have one question about react native. 1) How can I call another class inside a hooks? For example if I have:

import React, { Component, useEffect, useState} from 'react';
import { TextInput } from 'react-native-paper';
import {  View,Text} from 'react-native';
import Utils from './Utils';
export default function Userprofile() {
  const [text, setText] = useState("");
  const [sid, setSid] = useState("");

  useEffect(() => {
    var y = sid.getSid();
    setSid(t);
  }, []);
  return (
    <View>
      <TextInput label="" value={text} onChangeText={(text) => setText(text)} />
      <Text>il sid è: {sid}</Text>
    </View>
  );
}

and in Utils.js:

import React, { Component } from "react";
export default class Utils extends Component {
  constructor(props) {
    super(props);
  }
  async getSid() {
    try {
      var value = await AsyncStorage.getItem("sid");
      if (value !== null) {
        console.log("value second screen is:", value);
        return value;
      }
    } catch (error) {}
  }
  render() {}
}

how can I call the method of another class in a hooks?

First of all you do not have defined any custom hook in your example. You have a functional component named UserProfile and a class component named Utils which does not render anything.

It seems to me that you want to call getSid in the useEffect located inside UserProfile . There is no reason to implement this function inside the class component Utils .

Instead, separate your business logic from your UI by introducing a new custom hook.

I will call this hook useUtils .

export function useUtils() {
    const [sid, setSid] = React.useState();

    React.useEffect(() => {
        const load = async () => {
          try {
              const value = await AsyncStorage.getItem("sid");
              if (value !== null) {
                 setSid(value);
              }
          } catch (error) {}
        }
        load();
    }, [])

   return {
       sid,
   }
}

Then, use it as usual.

export default function Userprofile() {
  const [text, setText] = useState("");
  const {sid} = useUtils();

  if (!sid) {
    return null;
  }

  return (
    <View>
      <TextInput label="" value={text} onChangeText={(text) => setText(text)} />
      <Text>il sid è: {sid}</Text>
    </View>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM