简体   繁体   English

useState with interface- react native typescript

[英]useState with interface- react native typescript

there is a way to use useState with an interface type?有一种方法可以将 useState 与接口类型一起使用吗?

This is what i'm tryint to do:这就是我想做的:

const [movie, setMovie] = useState(null);

[...]

.then((responseJson) => {
            var movie: Movie = {
                id : id,
                title: responseJson.original_title,
                backdrop: "https://image.tmdb.org/t/p/original" + responseJson.backdrop_path,
                note: responseJson.vote_average,
                numberNote: responseJson.vote_count,
                year: responseJson.release_date,
                runtime: responseJson.runtime,
                genre: responseJson.genres,
                plot: responseJson.overview,
            };
            setMovie(movie);
        })

But there is error on type.但是类型有错误。

My interface:我的界面:

interface Movie {
    id: number;
    title: string;
    backdrop: string;
    note: number;
    numberNote: number,
    year: number,
    runtime: number,
    genre: {id: number, name: string}[],
    plot: string
}

according to this post: Set types on useState React Hook with TypeScript .根据这篇文章: Set types on useState React Hook with TypeScript

I can try to do something like that:我可以尝试做这样的事情:

const [movie, setMovie] = useState<Movie>({id: 0,
        title: "",
        backdrop: "",
        note: 0,
        numberNote: 0,
        year: 0,
        runtime: 0,
        genre: [{id: 0, name: ""}],
        plot: ""});

But it doesn't look clean and I don't think this is the good solution to put random value in the first state.但它看起来不干净,我认为这不是将随机值放在第一个 state 中的好解决方案。

You can imply state type in the following way:您可以通过以下方式暗示 state 类型:

const [movie, setMovie] = useState<Movie|null>(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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