Next.js重定向GraphQL变异

问题描述 投票:2回答:1

在我的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个回答
0
投票

您的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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.