【问题标题】:Next.js redirect inside of GraphQL mutationNext.js 在 GraphQL 突变内重定向
【发布时间】:2018-12-24 11:18:26
【问题描述】:

在我的 Next.js 组件中,我向 GraphQL 服务器发出了一个突变请求,成功完成后我需要重定向到另一个页面。我现在怎么做:

import React, { Component } from 'react';
import Router from 'next/router';
import { Mutation } from 'react-apollo';
import { gql } from 'apollo-boost';

const signInMutation = gql`
  mutation signIn($accessToken: String!) {
    signIn(accessToken: $accessToken)
  }
`;

export default class extends Component {
  static async getInitialProps({ query: { accessToken } }) {
    return { accessToken };
  }

  render() {
    const { accessToken } = this.props;
    return (
      <Mutation mutation={signInMutation} ignoreResults>
        {signIn => {
          signIn({ variables: { accessToken } }).then(() => {
            Router.push({
              pathname: '/user'
            });
          });

          return null;
        }}
      </Mutation>
    );
  }
}

它工作正常,但 Next.js 抛出错误:You should only use "next/router" inside the client side of your app.。那么,修复错误的最佳方法是什么?

【问题讨论】:

    标签: reactjs graphql apollo next.js


    【解决方案1】:

    您的 signIn 突变在渲染时执行,当 NextJS 在服务器端渲染您的应用时,执行您的突变。

    你应该渲染一个按钮,并且只在点击时触发突变:

    import React, { Component } from 'react';
    import Router from 'next/router';
    import { Mutation } from 'react-apollo';
    import { gql } from 'apollo-boost';
    
    const signInMutation = gql`
      mutation signIn($accessToken: String!) {
        signIn(accessToken: $accessToken)
      }
    `;
    
    export default class extends Component {
      static async getInitialProps({ query: { accessToken } }) {
        return { accessToken };
      }
    
      render() {
        const { accessToken } = this.props;
        return (
          <Mutation mutation={signInMutation} ignoreResults>
            {signIn => {
              return (
                <button onClick={async () => {
                  await signIn({ variables: { accessToken } })
                  Router.push({ pathname: '/user' })
                }}>Login</button>
              )
            }}
          </Mutation>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 2019-11-27
      • 1970-01-01
      • 2020-08-23
      • 2019-06-28
      • 2019-01-23
      • 2021-03-09
      • 2021-04-10
      相关资源
      最近更新 更多