簡體   English   中英

帶有React鈎子的If語句中出現意外的令牌語法錯誤

[英]Unexpected Token Syntax Error In If Statement With React Hooks

使用React Hooks時出現語法錯誤。 基本上,我在useEffect內使用If語句,並獲取和意外的令牌錯誤。

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

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

語法看起來很簡單,但是看起來我缺少一些東西。

參見codepen

if語句當前是您調用setLinkAnimation的參數

我認為您實際上正在嘗試執行以下操作:

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

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

您的setState函數期望某種值,而僅僅是一個函數(console.log)。 如果將其包裝在帶有隱式或顯式返回的粗箭頭函數中,則它將起作用。

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

編輯:請注意,這仍然不會設置狀態,但至少會完成您的console.log

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM