当我尝试使用router.query.xxx
访问查询字符串时,组件中的GraphQL查询未在动态路由上运行。
我有以下文件
// ./pages/section/[slug].js
import { useRouter } from 'next/router';
import AppLayout from '../../components/styles/_AppLayout';
const Section = () => {
const router = useRouter();
return <AppLayout>Hi</AppLayout>;
};
export default Section;
页面显示正常,但是一旦我添加{router.query.slug}
并刷新页面,它就会给我带来TypeError的错误,因为GraphQL查询不会运行。如下图所示,me.firstName
是未定义的,因为GraphQL查询未运行
这是_AppLayout.js
import styled from 'styled-components';
import Navigation from '../Navigation';
const Wrapper = styled.div`...`;
const AppLayout = props => {
return (
<Wrapper>
<Navigation />
<main>{props.children}</main>
</Wrapper>
);
};
export default AppLayout;
有什么想法可能会发生这种情况以及如何解决?
谢谢
答案 0 :(得分:0)
我能够通过两种方式解决问题
使用 withRouter
import { withRouter } from 'next/router';
import TestComponent from '../../components/TestComponent';
import AppLayout from '../../components/styles/_AppLayout';
const Section = props => {
return <AppLayout>Hi {props.query.slug}</AppLayout>;
};
export default withRouter(Section);
并将查询参数作为道具通过getInitialProps
const Section = ({slug}) => {
return <AppLayout>Hi {slug}</AppLayout>;
};
Section.getInitialProps = async ({ query }) => {
const { slug } = query;
return { slug };
};
export default Section;
答案 1 :(得分:0)
以下方法对我有用,我将React Hooks与Context结合使用,并且我还需要使用nextJS路由,因此可以遵循以下配置。
注意:如果您使用的是GraphQL,则也可以将其包装在_app.js中的最终JSX上
_app.js:
import { withRouter } from "next/router";
BuilderProvider是上下文提供程序
const InjectRouterContext = withRouter(({ router, children }) => {
return <BuilderProvider value={router}>{children}</BuilderProvider>;
});
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<InjectRouterContext>
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
</InjectRouterContext>
);
}
}
现在在页面中,这里是somepage.js:
import { useRouter } from "next/router";
const somepage = () => {
const router = useRouter();
const { id } = router.query;
return (//JSX Here);
}
somepage.getInitialProps = async ({ query }) => {
const { slug } = query;
return { slug };
};
export default somepage;