微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

社交登录 - 如何在反应中使用函数之外的变量?

如何解决社交登录 - 如何在反应中使用函数之外的变量?

我尝试使用社交登录

如果我成功登录 kakao。他们给了我 access_token,我用它来改变我的服务器

下面是我的代码

import { useMutation } from "react-apollo-hooks";
import { KAKAO_LOGIN } from "./AuthQuery";


export default () => {
  const kakaoLoginMutation = useMutation(KAKAO_LOGIN,{
    variables: { provder: "kakao",accesstoken: authObj.access_token },});

  const kakaoLogin = (e) => {
    e.preventDefault();
    window.Kakao.Auth.login({
      success: function (authObj) {
        console.log(authObj.access_token);
      },});
  };
  if (authObj.access_token !== "") {
    kakaoLoginMutation();
  }
  return (
    <a href="#" onClick={kakaoLogin}>
      <h1>카카오로그인</h1>
    </a>
  );
};

如果我使用 kakaoLogin 函数登录成功,它会给出 authObj。 console.log(authObj.access_token) 告诉我 access_token

我想用它来使用Mutation。但它向我显示 authObj 未定义。

解决方法

看起来您正在寻找一个地方州来持有 authObj

const [authObj,setAuthObj] = useState({});

const kakaoLogin = (e) => {
  e.preventDefault();
  window.Kakao.Auth.login({
    success: function(authObj) {
      setAuthObj(authObj);
    },});
};

const kakaoLoginMutation = useMutation(KAKAO_LOGIN,{
  variables: {
    provder: "kakao",accessToken: authObj.access_token
  },});

if (authObj.access_token !== "") {
  kakaoLoginMutation();
}
,

阅读Apollo auth docs(你读过,对吧?)之后,您应该知道应该使用标头发送令牌

...如果使用身份验证链接并从localStorage读取令牌 ...那么任何登录功能(变异、请求)结果都应结束将令牌存储在localStorage中 (在下一个查询/突变中通过标头传递)......应该很明显。

在这种情况下

...我们有一些不同的情况 - kakao 令牌作为变量传递给登录突变...

我们可以简单地直接(不使用状态、效果、重新渲染)将 kakao 令牌传递给“mutation caller” (node:7596) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block,or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection,use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) [0] > (node:7596) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. [0] > (node:7596) UnhandledPromiseRejectionWarning: Error: Value for argument "opStr" is invalid. Acceptable values are: <,<=,==,!=,>,>=,array-contains,in,not-in,array-contains-any ):>

kakaoLoginMutation

需要时,可以在 // mutation definition const [kakaoLoginMutation] = useMutation(KAKAO_LOGIN); // event handler const kakaoLogin = (e) => { e.preventDefault(); window.Kakao.Auth.login({ success: function(authObj) { // run mutation kakaoLoginMutation({ variables: { provder: "kakao",accessToken: authObj.access_token } }) },}); }; 处理程序中处理登录变更 (KAKAO_LOGIN) 结果

onCompleted

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。