无需返回或分派的Redux动作

时间:2020-05-11 00:25:20

标签: redux react-redux

我正在使用redux从google实现Oauth,我想从我的redux处理所有google API调用,最终在我的操作文件中编写了不返回任何内容或调用分派的辅助函数。我最终得到的代码中,我仅从JSX文件中调度一次,并且想知道这是否还可以,或者还有另一种更好的方法?

代码如下:
authActions.js


const clientId = process.env.REACT_APP_GOOGLE_OAUTH_KEY;
let auth;

export const authInit = () => (dispatch) => {
  window.gapi.load('client:auth2', () =>
    window.gapi.client.init({ clientId, scope: 'email' }).then(() => {
      auth = window.gapi.auth2.getAuthInstance();
      dispatch(changeSignedIn(auth.isSignedIn.get()));
      auth.isSignedIn.listen((signedIn) => dispatch(changeSignedIn(signedIn)));
    })
  );
};

export const signIn = () => {
  auth.signIn();
};

export const signOut = () => {
  auth.signOut();
};

export const changeSignedIn = (signedIn) => {
  const userId = signedIn ? auth.currentUser.get().getId() : null;

  return {
    type: SIGN_CHANGE,
    payload: { signedIn, userId },
  };
};

GoogleAuth.jsx

import { useSelector, useDispatch } from 'react-redux';
import classNames from 'classnames';
import { authInit, signIn, signOut } from '../../actions/authActions';

function GoogleAuth() {
  const { signedIn } = useSelector((state) => state.auth);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(authInit());
  }, [dispatch]);

  const onClick = () => {
    if (signedIn) {
      signOut();
    } else {
      signIn();
    }
  };

  let content;
  if (signedIn === null) {
    return null;
  } else if (signedIn) {
    content = 'Sign Out';
  } else {
    content = 'Sign In';
  }

  return (
    <div className="item">
      <button
        className={classNames('ui google button', {
          green: !signedIn,
          red: signedIn,
        })}
        onClick={onClick}
      >
        <i className="ui icon google" />
        {content}
      </button>
    </div>
  );
}

export default GoogleAuth;

代码可以正常工作,但是感觉在JSX中执行动作调用而不是分派代码可能会误导人,这样可以吗?

0 个答案:

没有答案