[英]Typescript/React-Native: Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'
I am learning typescript
with React-Native
and I want to use AsyncStorage
library.我正在学习
typescript
和React-Native
并且我想使用AsyncStorage
库。 When setting my state after reading value from the storage, I got this problem:从存储读取值后设置我的 state 时,我遇到了这个问题:
const value: string |
常量值:字符串 | null Argument of type 'string |
null 类型参数 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'.
null' 不可分配给“SetStateAction<never[]>”类型的参数。 Type 'null' is not assignable to type 'SetStateAction<never[]>'
类型“null”不可分配给类型“SetStateAction<never[]>”
The App is showing the value but I want to learn how to solve the problem.该应用程序正在显示价值,但我想学习如何解决问题。 I guess I have to assign a
type
to the useState
, but do not know how to assign SetStateAction
type.我想我必须为
useState
分配一个type
,但不知道如何分配SetStateAction
类型。
How do I set the type to the useState
to solve this problem?如何将类型设置为
useState
来解决这个问题?
This is the sample code:这是示例代码:
import React, {useEffect, useState} from 'react';
import {Text, View} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const App = () => {
const [value, setValue] = useState([]);
async function saveValue(key: string, value: string) {
await AsyncStorage.setItem(key, value);
}
async function readValue(key: string) {
const value = await AsyncStorage.getItem(key);
setValue(value);
}
useEffect(() => {
saveValue('123', 'Hello world! ');
readValue('123');
}, []);
return (
<View>
<Text>{value}</Text>
</View>
);
};
export default App;
Thank you.谢谢你。
Using const [value,setValue] = useState<string | null>('');
使用
const [value,setValue] = useState<string | null>('');
const [value,setValue] = useState<string | null>('');
fixed the issue as suggested by @Mic Fung.按照@Mic Fung 的建议解决了这个问题。 This is the resulting code:
这是生成的代码:
const App = () => {
const [value, setValue] = useState<string | null>('');
async function saveValue(key: string, value: string) {
await AsyncStorage.setItem(key, value);
}
async function readValue(key: string) {
const value = await AsyncStorage.getItem(key);
setValue(value);
}
useEffect(() => {
saveValue('123', 'Hello world! ');
readValue('123');
}, []);
return (
<View>
<Text>{value}</Text>
</View>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.