简体   繁体   中英

I wanted to convert my react class component to a functional component using react hooks. it gave an error like below

I wanted to convert my react class component to a functional component using react hooks. it gave an error like below.

Failed to compile
./src/templates/addPost.js
  Line 6:29:  React Hook "useState" is called in function "addPost" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error. This error occurred during the build time and cannot be dismissed.

my code is :

const AddPost  = (props)=> {
const [post, setPost] = useState({
    id: Math.random(),
    title: '',
    body: ''
})

const handleInput = (target, value) =>{
    return {
        id: post.id,
        title: target.id == 'title' ? value : post.title,
        body: target.id == 'body' ? value : post.body
    }
}

const handleSubmit = (e)=>{
    e.preventDefault()
    console.log(post)
    props.actionPost(post)
    e.target.reset()
    props.history.push('/post/'+ post.id)
}
  

 return ( <form onSubmit={handleSubmit}>
           <input onChange={(e)=>{setPost(handleInput(e.target, e.target.value))}}  type="text" id='title'/>
                            
          <input onChange={(e) => { setPost(handleInput(e.target, e.target.value))}} type="text" id='body'/>
                            
          <button type="submit" onSubmit={handleSubmit}>Submit</button>
         </form>)

}

const mapDispatchToProps = (dispatch) =>{
    return {
        actionPost: (post)=>{
            dispatch(addPostAction(post))
        }
    }
}
export default connect(null, mapDispatchToProps)(AddPost)

如果 addPost 是组件,则“a”应为大写。每个组件名称应以大写字母开头。

const AddPost  = (props)=>

You can only use a hook in a React Component. Generally, it's good style to create your functional components to have a PascalCase name, and the Rule of Hooks eslint rules enforce this.

This is the code from eslint-plugin-react-hooks that is responsible for producing that error message.

/**
 * Checks if the node is a React component name. React component names must
 * always start with a non-lowercase letter. So `MyComponent` or `_MyComponent`
 * are valid component names for instance.
 */

function isComponentName(node) {
  if (node.type === 'Identifier') {
    return !/^[a-z]/.test(node.name);
  } else {
    return false;
  }
}

So, Rule of Hooks does not consider any function that starts with a lowercase letter to be a Functional Component.

This style of functional components is enforced by ESLint at transpile time. Here's an example of a functional component doing what you are trying to do.

export const AddPost = (props) => {
  const [post, setPost] = useState({
    id: Math.random(),
    title: "",
    body: "",
  });

  const handleInput = (target, value) => {
    return {
      id: post.id,
      title: target.id == "title" ? value : post.title,
      body: target.id == "body" ? value : post.body,
    };
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(post);
    props.actionPost(post);
    e.target.reset();
    props.history.push("/post/" + post.id);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        onChange={(e) => {
          setPost(handleInput(e.target, e.target.value));
        }}
        type="text"
        id="title"
      />

      <input
        onChange={(e) => {
          setPost(handleInput(e.target, e.target.value));
        }}
        type="text"
        id="body"
      />

      <button type="submit" onSubmit={handleSubmit}>
        Submit
      </button>
    </form>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM