简体   繁体   中英

React Hook “useState” is called in function

I have button click system and it works.

function clickCreate(msg){
    console.log(msg);
}
const CreateButton = (props) =>{
  return(
    <div>
    <i onClick = {() => clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt"></i>
    </div>
  );
}

Now I want to fetch the API inside the function.

So, change the function clickCreate like this

function clickCreate(msg){
  const [result, setResult] = useState([]);
  useEffect(() => {
    axios.get('http://localhost:8000/api/genres/')
      .then((res)=> {
      console.log(res.data.items);
      setResult(res.data.items);
    }).catch(err=>{console.log(err);});
  }, []);
}

However there comes error like this.

I should not use useState and useEffect in function, but how can trigger the API by btn click??

./src/views/Components/Components.js
  Line 168:31:  React Hook "useState" is called in function "clickCreate" which is neither a React function component or a custom React Hook function   react-hooks/rules-of-hooks
  Line 170:3:   React Hook "useEffect" is called in function "clickCreate" 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.

You should move the hook to component level ( Rules of hooks ), then you can fetch on click and use the hook's setter:

const CreateButton = (props) => {
  const [result, setResult] = useState([]);

  // should be in scope with `setResult`
  function clickCreate() {
    axios
      .get("http://localhost:8000/api/genres/")
      .then((res) => {
        console.log(res.data.items);
        setResult(res.data.items);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  return (
    <div>
      <i
        onClick={clickCreate}
        id="createBtn"
        className="fas fa-5x fa-microphone-alt"
      ></i>
    </div>
  );
};

I think a better approach would be to move the function in the component and take useState out.

const CreateButton = (props) =>{
  const [result, setResult] = useState([]);

  const clickCreate = async (msg) => {
      console.log(msg);
      let res = await axios.get('http://localhost:8000/api/genres/');
      setResult(res.data.items);
  }

  return(
    <div>
    <i onClick = {() => clickCreate("test")} id="createBtn" className="fas fa-5x fa-microphone-alt"></i>
    </div>
  );
}

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