Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - 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.
question from:https://stackoverflow.com/questions/65643375/react-hook-usestate-is-called-in-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...