2 回答

TA貢獻1835條經驗 獲得超7個贊
根據文檔https://reactjs.org/docs/hooks-rules.html
從 React 函數組件調用 Hooks
在你的情況下,你的函數不是一個組件,它是一個返回組件的函數
您可以更改代碼以擺脫 HOC 并使用帶有children
prop的簡單組合
import React, { useState } from 'react';
export default function TinderCard({children}) {
const [isLoading, setIsLoading] = useState(false);
const refresh = () => {
// change state. set isLoading to true and then back to false.
setIsLoading(true);
setIsLoading(false);
};
return (
<div className='card user-card-container'>
<div className='card-body user-card-inner'>
{isLoading ? <h3>Loading...</h3> : children}
<div className='buttons-container'>
<button className='dislike' onClick={() => refresh()}>
<i className='fa fa-times'></i>
</button>
<button className='like' onClick={() => refresh()}>
<i className='fa fa-heart'></i>
</button>
</div>
</div>
</div>
);
}
然后像這樣使用它:
<TinderCard>
<SomeFriend/>
</TinderCard>

TA貢獻1865條經驗 獲得超7個贊
https://codesandbox.io/s/react-hooks-usestate-forked-6pqw7
看起來上面的答案提供了問題的部分解決方案,但我只是想指出您的解決方案中可能存在的另一個問題。您的刷新函數調用 setIsLoading 兩次。這將導致組件重新渲染,但只會發生一次,并且只會在刷新函數完成執行后發生。您的組件永遠不會在狀態變量實際為 true 的情況下呈現。此外,與狀態變量的 useEffect 掛鉤相關的任何效果也不會在刷新時執行。有關如何發生這種情況的示例,請參閱上面的代碼沙箱。
添加回答
舉報