is it possible to React.useState(() => {}) in React?

后端 未结 2 761
一向
一向 2021-02-02 09:03

is it possible to use a function as my React Component\'s state ?

example code here:

// typescript 
type OoopsFunction = () => void;

exp         


        
2条回答
  •  别跟我提以往
    2021-02-02 09:33

    The implementation of useState in React is

    export function useState(initialState: (() => S) | S) {
      const dispatcher = resolveDispatcher();
      return dispatcher.useState(initialState);
    }
    

    It shows, that you can indeed use a function as parameter and this function has to return a type S. In your case S would be undefined, because () => console.log(...) returns nothing, although you explicitly specified it as OoopsFunction.

    So if you want to store a function as state via useState you have to implement Tholle's approach, where the function actually returns a function and not undefined.

提交回复
热议问题