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 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
.
本文标签: javascriptUnexpected Token Syntax Error In If Statement With React HooksStack Overflow
版权声明:本文标题:javascript - Unexpected Token Syntax Error In If Statement With React Hooks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745589752a2665127.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论