admin管理员组

文章数量:1431692

I'm getting a syntax error in when using React Hooks. Basically, I'm using an If statement inside useEffect and getting and Unexpected token error.

const [linkAnimation, setLinkAnimation] = useState();
const [isHovered, setIsHovered] = useState(true);

useEffect(() => {
    setLinkAnimation( 
      if(isHovered === true){  //getting unexpected token on this line
        console.log('true')
      }
    );
}, []); 

Syntax seems straight forward, but looks like I'm missing something.

See codepen

I'm getting a syntax error in when using React Hooks. Basically, I'm using an If statement inside useEffect and getting and Unexpected token error.

const [linkAnimation, setLinkAnimation] = useState();
const [isHovered, setIsHovered] = useState(true);

useEffect(() => {
    setLinkAnimation( 
      if(isHovered === true){  //getting unexpected token on this line
        console.log('true')
      }
    );
}, []); 

Syntax seems straight forward, but looks like I'm missing something.

See codepen

Share Improve this question asked Aug 16, 2019 at 17:16 Eric NguyenEric Nguyen 1,0464 gold badges17 silver badges44 bronze badges 2
  • 1 the syntax is wrong. see Expressions versus statements in JavaScript – Aprillion Commented Aug 16, 2019 at 17:19
  • 1 setLinkAnimation is a function, and you are passing a if statement as an argument to the function. Error is expected. – user9408899 Commented Aug 16, 2019 at 17:21
Add a ment  | 

2 Answers 2

Reset to default 3

The if statement is currently the parameter for your call to setLinkAnimation

I think you're actually trying to do something like this:

const [linkAnimation, setLinkAnimation] = useState();
const [isHovered, setIsHovered] = useState(true);

useEffect(() => {
  if(isHovered === true){  //getting unexpected token on this line
    console.log('true')
    setLinkAnimation(true);
  }
}, []); 

Your setState function is expecting a value of some sort, but instead is just a function (console.log). If you wrap it in a fat arrow function with an implicit or explicit return, it works.

useEffect(() => {
    setLinkAnimation( () => {
      if(isHovered === true){
        console.log('true')
      }
    });
}, []); 

Edit: Please note that this will still not set the state, but it will at least plete your console.log.

本文标签: javascriptUnexpected Token Syntax Error In If Statement With React HooksStack Overflow