Set types on useState React Hook with TypeScript

后端 未结 4 1880
一向
一向 2020-12-08 03:37

I\'m migrating a React with TypeScript project to use hooks features (React v16.7.0-alpha), but I cannot figure out how to set typings of the destructured elements.

4条回答
  •  醉话见心
    2020-12-08 04:13

    First useState takes a generic, which will be your IUser. If you then want to pass around the second destructured element that is returned by useState you will need to import Dispatch. Consider this extended version of your example that has a click handler:

    import React, { useState, Dispatch } from 'react';
    
    interface IUser {
      name: string;
    }
    
    export const yourComponent = (setUser: Dispatch) => {
    
        const [user, setUser] = useState({name: 'Jon'});
    
        const clickHander = (stateSetter: Dispatch) => {
            stateSetter({name : 'Jane'});
        }
    
        return (
             
    ) }

    See this answer.

提交回复
热议问题