You will learn

  1. Use a simple example to practice the use of interface and deepen your understanding of interface

object-oriented

Those of you who have some familiarity with TypeScript, “duck types,” and the React stack

The difficulty coefficient

⭐ ⭐

The body of the

This article focuses on interface practices, not code styles and other optimizations. React pseudocode is used to express the author’s ideas.

Let’s start with the simplest operation

  1. Use interface to constrain component parameters

    For example, if we need to display a user’s information on a page, the user has two fields, id and name, which are usually written like this

    import React from "react";
    interface Props {
    		user:{
    			id: string;
    	    name: string;
    		}
    }
    const index = (props: Props) => {
    		const user = props.user;
        return (
            <div>
                id:{user.id}--name:{user.name}
            </div>
        );
    };
    
    export default index;
    Copy the code

    One small detail, regarding the declared location of the interface User, should be placed in this component, or should it be extracted separately? I prefer to separate them out, either in a SRC /interface folder or in a directory that conforms to your project’s rules. Interfaces and components should not be written to a single file unless you really only use them within that component. Here I put the interface in SRC /user.ts

    user.ts

    export interface User {
        id: string;
        name: string;
    }
    Copy the code

    This interface is then referenced within the component

    import React from "react";
    import User from "@/interface/user";
    interface Props {
    		user:User
    }
    const index = (props: Props) => {
    		const user = props.user;
        return (
            <div>
                id:{user.id}--name:{user.name}
            </div>
        );
    };
    
    export default index;
    Copy the code
  2. Display a list of users

    Instead of just displaying a user’s information, how do we use interfaces to display a list of users? First create a file and introduce the corresponding interface(which is why you can see why interface declaration should be separate) and component Item(which is used to display user information). Declare a user list variable for rendering

    list.tsx

    import React,{useState,useEffect} from "react"; import User from "@/interface/user"; import Item from "./item"; const index = () => { const [userList,setUserList] = useState<Array<User>>([]); Const initData = ()=> {// pseudo-code... let arr = []; for(let i = 0; i<10; I ++){let item = {id: I,name:" I "+ I}; arr.push(item); } return arr; } useEffect(()=>{ let arr = initData(); setUserList(arr); } []); Return (<div> <p> list </p> {userlist.map (user=>{//user) Return <item user={user} />; }) } </div> ); }; export default index;Copy the code

    *useState<Array>, * means that the object created is an Array of items that match the User Interface object.

  3. Call the server API

    How do YOU use an interface when calling a server-side API? For example, if we want to get a list of users, the API address is/API /userList. This API accepts three parameters: pageNumber, pageSize, and Status. Create an interface that meets the parameters

    export interface UserListParams{
    	pageNumber:number;
    	pageSize:number;
    	status:number;
    }
    Copy the code

    So where should I put this interface? I did put it in interface/user.ts file. Another thing to consider is that common properties like pageNumber and pageSize can be extracted and inherited

    export interface Page{
    	pageNumber:number;
    	pageSize:number;
    }
    Copy the code

    inheritance

    import type { Page } from "@/interface/base";
    export interface UserListParams extends Page{
    	status:number;
    }
    Copy the code

    This way, other paging queries can be implemented by inheriting Page, for example, if you have other necessary public attributes to optimize your code.

    This interface is then introduced when the API is called to constrain the parameters of the function, for example

    import type { UserListParams } from "@/interface/user";
    export getUserList = (userListParams:UserListParams) =>{request("/api/userList",userListParams)}
    Copy the code

    Once the request method is defined, it can be invoked at the business layer as follows

    import React,{useState,useEffect} from "react"; import Item from "./item"; import type { UserListParams, User } from "@/interface/user"; import { getUserList } from "@/api/user"; const index = () => { const [userList,setUserList] = useState<Array<User>>([]); const [userListParams,setUserListParams] = useState<UserListParams>({ pageNumer:1, pageSize:10, status:0 }); useEffect(()=>{ const res = await getUserList(userListParams); },[userListParams]); Return (<div> <p> list </p> {userlist.map (user=>{//user) Return <item user={user} />; }) } </div> ); }; export default index;Copy the code

conclusion

Ah, the migrant workers are very hard, bengbu to live