【问题标题】:Typescript: property "title" does not exist on type 'never'打字稿:“从不”类型上不存在属性“标题”
【发布时间】:2020-08-13 04:22:29
【问题描述】:

我正在练习 React-native 打字稿。我从jsonplaceholer API 获取数据并添加到我的组件状态。映射状态并尝试在我的手机上渲染后。但我在终端上收到打字稿错误:property "title" does not exist on type 'never'

这是我的应用组件

import React, { useState, useEffect } from "react";
import { StyleSheet, Text, View, ScrollView, Image } from "react-native";

export default function App() {
  const [state, setstate] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/photos");
    const data = await response.json();
    setstate(data);
  };

  return (
    <ScrollView style={styles.body}>
      <View style={styles.container}>
        {state.map(list => {
          return <Text>{list.title}</Text>; //
        })}
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  body: {
    padding: 150
  },
  container: {
    flex: 1,
    backgroundColor: "white",
    alignItems: "center",
    justifyContent: "center"
  },

  stretch: {
    width: 50,
    height: 200,
    resizeMode: "stretch"
  }
});

【问题讨论】:

    标签: typescript react-native expo


    【解决方案1】:

    您必须将您的状态定义为 any 类型的数组:

    const [state, setstate] = useState([] as any[]);
    

    默认情况下,TypeScript 将空数组定义为never[]。那是一个永远为空的数组。 TS的奇怪之处。更多信息在this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 2021-09-07
      • 2020-09-28
      • 1970-01-01
      • 2017-08-07
      • 2017-03-26
      • 2017-09-06
      相关资源
      最近更新 更多