Shopify - 如何在页面之间路由

时间:2021-06-17 12:36:05

标签: react-router shopify shopify-app

我是 Shopify 应用开发的新手,我尝试在我的嵌入式 Shopify 应用中实现路由。

我已经设置了 ClientRouter 并将它集成到 app.js 中(见下文)。当我通过合作伙伴帐户设置导航链接时,会出现导航菜单,链接和重定向也能正常工作。

当我尝试通过单击按钮将用户导航到页面时,我收到错误消息:

<块引用>

需要一个有效的商店查询参数

我试图通过提供页面路径来导航用户:

<Button url="/users">Users</Button>

我的其他文件如下:

index.js

import { Page, Heading, Button } from "@shopify/polaris";

const Index = () => (
  <Page>
    <Heading>Index PAGE</Heading>
    <Button url="/users"> Users </Button>
  </Page>
);

export default Index;
app.js

import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import App from "next/app";
import { AppProvider } from "@shopify/polaris";
import { Provider, useAppBridge } from "@shopify/app-bridge-react";
import { authenticatedFetch } from "@shopify/app-bridge-utils";
import { Redirect } from "@shopify/app-bridge/actions";
import "@shopify/polaris/dist/styles.css";
import translations from "@shopify/polaris/locales/en.json";
import ClientRouter from "../components/ClientRouter";

function userLoggedInFetch(app) {
  const fetchFunction = authenticatedFetch(app);

  return async (uri, options) => {
    const response = await fetchFunction(uri, options);

    if (
      response.headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1"
    ) {
      const authUrlHeader = response.headers.get(
        "X-Shopify-API-Request-Failure-Reauthorize-Url"
      );

      const redirect = Redirect.create(app);
      redirect.dispatch(Redirect.Action.APP, authUrlHeader || `/auth`);
      return null;
    }

    return response;
  };
}

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: userLoggedInFetch(app),
    fetchOptions: {
      credentials: "include",
    },
  });

  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}

class MyApp extends App {
  render() {
    const { Component, pageProps, host } = this.props;

    return (
      <AppProvider i18n={translations}>
        <Provider
          config={{
            apiKey: API_KEY,
            host: host,
            forceRedirect: true,
          }}
        >
          <ClientRouter />
          <MyProvider Component={Component} {...pageProps} />
        </Provider>
      </AppProvider>
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    host: ctx.query.host,
    API_KEY: process.env.SHOPIFY_API_KEY,
  };
};

export default MyApp;
ClientRouter.js

import { withRouter } from "next/router";
import { ClientRouter as AppBridgeClientRouter } from "@shopify/app-bridge-react";

function ClientRouter(props) {
  const { router } = props;
  return <AppBridgeClientRouter history={router} />;
}

export default withRouter(ClientRouter);

我真的很期待有人可以帮助我!提前致谢!

0 个答案:

没有答案