javascript - 在 react-native 上使用 useEffect 挂钩的无限循环
问题描述
我在 ReactJS 上的 useEffect 有一个奇怪的行为。我将它用于“componentDidMount”事件:
index.js from Home
useEffect(() => {
console.log(isAuthenticated)
dispatch(Actions.checkIfTokenHasExpired());
}, []);
问题是在 react-native 上它会启动一个无限循环,一直在重新创建组件。useEffect 在 RN 中的工作方式是否不同?如果是这样,我该如何解决?
我还意识到,如果在我的操作中返回一个函数,就会发生循环,如下所示:
actions.js
export function checkIfTokenHasExpired() {
return async dispatch => {
try {
dispatch(showLoader(true));
await Api({ accessToken: helper.accessToken }).post('account/check_if_token_has_expired', { /*body*/ });
dispatch({
type: Types.CHECK_IF_TOKEN_HAS_EXPIRED,
isAuthenticated: true
});
} catch (err) {
dispatch(handleActionError(err));
}
}
}
有任何想法吗?
编辑:应用程序结构:
App.js
| src
| | index.js
| | |
| | actions
| | | index.js
| | components
| | | screens
| | | | Home
| | | | | index.js
EDIT²:来自 Home.js 的 index.js 的 JSX:
export default function Home(props) {
const dispatch = useDispatch();
const { isAuthenticated } = useSelector(state => state.auth);
useEffect(() => {
dispatch(Actions.checkIfTokenHasExpired());
}, []);
return (
<View>
<BigLogo source={logo} />{/*a simple styledComponent with ImageBackground*/}
<LoginCard {...props} />{/*a login panel*/}
</View>
)
解决方案
推荐阅读
- r - R:在for循环中命名矩阵行/列在控制台中有效,但在编织时无效
- excel - 随机分布到一个矩阵
- python - 如何在 Matplotlib 中注册倒数(1/x)比例?
- google-sheets - 为几个不同的行(数组)创建单个公式(谷歌表格)
- ios - 对如何/在哪里设置 Xib 的高度感到困惑
- matlab - 调用期间未分配输出参数:Matlab
- java - 如何使用 Intent android studio 打开whatsapp 或whatsapp 业务?
- javascript - 在前端 Angular 中使用 Python Pillow
- python - 如何在 Python Poetry 中指定对操作系统的依赖关系?
- java - 当我尝试将类的内容添加到数组时程序崩溃