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

后端 未结 2 701
一向
一向 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<S>(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.

    0 讨论(0)
  • 2021-02-02 09:55

    It is possible to set a function in state using hooks, but because state can be initialized and updated with a function that returns the initial state or the updated state, you need to supply a function that in turn returns the function you want to put in state.

    const { useState } = React;
    
    function App() {
      const [ooops, setOoops] = useState(() => () => console.log("default ooops"));
    
      return (
        <div>
          <button onClick={ooops}>Show Ooops</button>
    
          <button
            onClick={() => {
              setOoops(() => () => console.log("other ooops"));
            }}
          >
            change oops
          </button>
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <div id="root"></div>

    0 讨论(0)
提交回复
热议问题