繁体   English   中英

Typescript/React-Native:'string | 类型的参数 null' 不可分配给“SetStateAction”类型的参数<never[]> '</never[]>

[英]Typescript/React-Native: Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'

我正在学习typescriptReact-Native并且我想使用AsyncStorage库。 从存储读取值后设置我的 state 时,我遇到了这个问题:

常量值:字符串 | null 类型参数 'string | null' 不可分配给“SetStateAction<never[]>”类型的参数。 类型“null”不可分配给类型“SetStateAction<never[]>”

该应用程序正在显示价值,但我想学习如何解决问题。 我想我必须为useState分配一个type ,但不知道如何分配SetStateAction类型。

如何将类型设置为useState来解决这个问题?

这是示例代码:

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;


谢谢你。

使用const [value,setValue] = useState<string | null>(''); const [value,setValue] = useState<string | null>(''); 按照@Mic Fung 的建议解决了这个问题。 这是生成的代码:

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.

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