繁体   English   中英

在 React + Next.js + Typescript 中访问通过 URL 传递的 props

[英]Access to props passed by URL in React + Next.js + Typescript

使用 Typescript 时,我找不到访问通过 URL 传递的道具的方法。 显示最少代码来说明问题。

  1. 我正在推送一个页面:
Router.push('/task/[uuid]', '/task/' + data.uuid);
  1. 然后在/task/[uuid].tsx
export default class App extends React.Component<Props, State> {

    constructor(props: Props) {
        super(props);
        console.log(props); // {uuid: "", url: {…}}
    }

    componentDidMount() {
        console.log(this.props); // {uuid: "", url: {…}}
        if (!this.props.uuid) {
             throw new Error("Missing UUID");
        }
    }

    static getInitialProps({ req }: NextPageContext) {
        console.log(req); // undefined
    }

}

最奇怪的是,当推送URL时,它首先抛出错误,在浏览器中显示错误,但有时它会在几秒钟后恢复并成功。

当直接从浏览器调用 URL 时, uuid 在constructor()componentDidMount()都正确可用,但甚至没有调用getInitialProps()

我的问题:

  1. 这样做的正确方法是什么?
  2. 有 props.url,我可以将其用作解决方法。 能够访问它的正确类型是什么?
  3. 知道为什么它有时会“恢复”吗?
  4. 为什么直接从浏览器调用 URL 会起作用?
  5. 为什么在直接调用 URL 时不调用 getInitialProps()?

应该是query

static getInitialProps({ query }: NextPageContext) {
    console.log(query); // undefined
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM