[英]call the method of another class in a hooks
hi everyone i have one question about react native.大家好,我有一个关于 React Native 的问题。 1) How can I call another class inside a hooks?
1)如何在挂钩内调用另一个 class ? 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:在 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?如何在钩子中调用另一个 class 的方法?
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.您有一个名为
UserProfile
的功能组件和一个名为Utils
的 class 组件,它们不呈现任何内容。
It seems to me that you want to call getSid
in the useEffect
located inside UserProfile
.在我看来,您想在位于
UserProfile
的useEffect
中调用getSid
。 There is no reason to implement this function inside the class component Utils
.没有理由在 class 组件
Utils
中实现这个 function 。
Instead, separate your business logic from your UI by introducing a new custom hook.相反,通过引入一个新的自定义挂钩将您的业务逻辑与您的 UI 分开。
I will call this hook useUtils
.我将把这个钩子
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.