React Hook “useState” is called in function “app” which is neither a React function component or a custom React Hook function

前端 未结 29 984
花落未央
花落未央 2020-11-30 00:07

I\'m trying to use react hooks for a simple problem

const [personState,setPersonState] = useState({ DefinedObject });

with following depend

29条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 00:53

    Do not use arrow function to create functional components.

    Do as one of the examples below:

    function MyComponent(props) {
      const [states, setStates] = React.useState({ value: '' });
    
      return (
         setStates({ value: event.target.value })}
        />
      );
    }
    

    Or

    //IMPORTANT: Repeat the function name
    
    const MyComponent = function MyComponent(props) { 
      const [states, setStates] = React.useState({ value: '' });
    
      return (
         setStates({ value: event.target.value })}
        />
      );
    };
    

    If you have problems with "ref" (probably in loops), the solution is to use forwardRef():

    // IMPORTANT: Repeat the function name
    // Add the "ref" argument to the function, in case you need to use it.
    
    const MyComponent = React.forwardRef( function MyComponent(props, ref) {
      const [states, setStates] = React.useState({ value: '' });
    
      return (
         setStates({ value: event.target.value })}
        />
      );
    });
    

提交回复
热议问题