Next.js在GraphQL突变内部重定向

时间:2018-07-16 20:39:51

标签: reactjs graphql apollo next.js

在我的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.。那么,解决错误的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

您的signIn变异在render上执行,当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>
    );
  }
}