首页 > 解决方案 > 在 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>
)

标签: javascriptreact-nativeredux

解决方案


推荐阅读