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 aif statement
as an argument to the function. Error is expected. – user9408899 Commented Aug 16, 2019 at 17:21
2 Answers
Reset to default 3The 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
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745589753a4634761.html
评论列表(0条)