【问题标题】:.map with typescript, where to insert the interface?带有打字稿的.map,在哪里插入界面?
【发布时间】:2019-12-18 03:06:15
【问题描述】:

尝试使用 React、NextJS 和 Typescript 做一些事情。我遇到了一个问题,我不断收到“类型'boolean | any []'上不存在x。类型'false'.ts(2339)上不存在属性'x'”错误。我只是不知道在哪里放置界面以显示它使用的是什么类型。谁能帮我吗?这是有问题的代码!

Articles.js

import React, { FunctionComponent } from 'react'; // we need this to make JSX compile
import useFetch from '../hooks/fetch'
type artProps = {
    title: string,
    author: string,
    date: number
}
type article = {
    title: string,
    author: string,
    date: number
}

export const Articles: FunctionComponent<{artProps}> = () => {
    const url = 'http://localhost:4000/kb'

    const data = useFetch(url)
    console.log(data)
    return (
        <div>
            {data.map(articles) => {
                return (<div key={article.id}>
                    {console.log(article)}
                    <h2 key={article.id}>{article.title} </h2>
                    <p key={article.id}>{article.body}</p>
                </div>
                )
            })}
            {/* {artProps.map(artProp => {
                return (
                    <div>
                        <h2>{artProp.title}</h2>
                        <p>{artProp.author}</p>
                    </div>
                )
            })
            } */}
        </div>
    )
}
export default Articles

钩子

import React, { useState, useEffect } from 'react';
import axios from 'axios';


const useFetch = (url) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        console.log('fetch')
        axios.get(url)
            .then(res => {
                if (res.data) {
                    setData(res.data)
                    setLoading(false)
                }
            })
    }
        , []);


    return [data, loading];
};

export default useFetch

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:
    import React, { useState, useEffect } from 'react';
    import axios from 'axios';
    
    
    const useFetch = <T>(url: string): [T, boolean] => {
        const [data, setData] = useState([]);
        const [loading, setLoading] = useState(true);
    
        useEffect(() => {
            console.log('fetch')
            axios.get(url)
                .then((res: any) => {
                    if (res.data) {
                        setData(res.data)
                        setLoading(false)
                    }
                })
        }
            , []);
    
    
        return [data, loading];
    };
    
    export default useFetch
    

    现在将它添加到父组件...

    useFetch<ArrayTypeHere>(url)
    

    现在 .map 将推断出正确的类型,无需注释或类型转换。

    【讨论】:

    • 这给了我很多错误。我正在使用 CRA,我无法在没有很多错误的情况下将其加载到 tsx 中。无法使用 .ts
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2018-07-18
    • 2018-02-04
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多