【问题标题】:Property does not exist on type 'never' on JSON arrayJSON数组上的“从不”类型不存在属性
【发布时间】:2021-05-18 03:39:49
【问题描述】:

我只是想从一个 url 获取一些 JSON 数据。 JSON 数据的格式如下(为简单起见减少为两个条目):

[
  {
    "id": 1
    "name": "Brett",
    "gender": "male"
   },
  {
    "id": 2
    "name": "Sandra",
    "gender": "female"  
  }
]

我可以使用console.log(profiles) 打印profiles 并查看控制台中的所有条目,但是当我尝试访问 .name 字段时出现错误

Property 'name' does not exist on type 'never'.

这是应用程序的代码:

const URL = 'someurl'

function App() {
    const [curId, setId] = useState(0);
    //const [curProfile, setCurProfile] = useState(undefined);
    const [profiles, setProfiles] = useState([])

    useEffect(() => {
        fetch(URL)
            .then((response) => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error("Something went wrong!");
                }
            })
            .then(
                (response) => {
                    setProfiles(response);
                    setId(1);
                    //setCurProfile(profiles[curId - 1]);
            })
            .catch((error) => {
                console.log(error)
            })
    }, []);

    return (
    <div className="App">
        <p>
            {profiles[curId].name}
        </p>
    </div>
  );
}

export default App;

另外作为一个附带问题,我在将当前配置文件存储在 curProfile 变量中时遇到了一些问题。有人可以为我指出正确的方向吗?谢谢!

【问题讨论】:

    标签: json reactjs typescript


    【解决方案1】:

    profiles 的初始状态为空数组,curId 为 0,所以 profiles[curId] 应该是未定义的,因此 profiles[curId].name 在初始渲染时会出错。

    您应该始终检查profiles 是否为空。

    return (
        <div className="App">
            {profiles.length > 0 &&
               <p>
                {profiles[curId].name}
               </p>
            }
        </div>
    )
    

    【讨论】:

      【解决方案2】:

      你必须输入你的状态,否则 Typescript 将不知道会发生什么。您还需要输入响应。

      类似:

      type Profile = {
        id: number,
        name: string,
        gender: string
      }
      
      const [profiles, setProfiles] = useState <Profile[]> ([]);
      
      (...)
      
      setProfiles(response as Profile[]);
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 2016-02-28
        • 1970-01-01
        • 1970-01-01
        • 2017-10-24
        • 2018-02-10
        • 2017-01-14
        • 2021-12-30
        • 2017-04-09
        相关资源
        最近更新 更多