【问题标题】:How to fetch data using link in Nextjs如何使用 Nextjs 中的链接获取数据
【发布时间】:2020-03-09 17:54:51
【问题描述】:

我的数据存储在 Mongo Atlas 中。我可以获取数据(帖子),但是当我点击帖子时,它不会为我提供该 ID 的数据。我创建了一个页面/帖子页面。由于下面的代码位于 postlist.tsx 中,我只能查看帖子的 ID,并且只能通过其 url 将 ID 传递到下一页。我还希望能够查看与该特定 ID 关联的帖子的标题和正文:

这是我的 blogs.tsx

    interface PostState{
        posts: Post[];
    }

    export default class PostList extends React.Component <{},PostState> {
            state = {
                posts: []
            };

            componentDidMount = () => {
                this.getBlogPost();
            };

            getBlogPost = () => {

                axios
                    .get('/api')
                    .then(({data}) => {
                        const reverseData = new Array;
                        for (let datetime = data.length - 1; datetime >= 0; datetime--) {
                            reverseData.push(data[datetime]);
                        }
                        this.setState({posts: reverseData})
                    })
                    .catch((error) => {
                        alert('Error: there was an error processing your request')
                    })
            }

            displayBlogPost = (posts : Post[]) => {
                const currentDateTime = new Date();
                if (!posts.length) 
                    return null;

                return posts.map((post, index) => (
                    <div key={index}>
                        <Card>
                        <Title> 

                            <Link href={`/post?id=${post._id}`} as= . 
       {`/post/${post._id}`}></Title>
                        {/* <p>{post.date}</p>
                        <p>{post.name}</p> */}

                        <FullName>{`${post.name} | 
       ${dateToString(currentDateTime)}`}</FullName>
                        <Line />
                        <Question >{post.body}</Question>
                        </Card>
                    </div>
                ));
            }

            render() {
                return (
                    <div>
                        <Container>
                        <Headers/>
                        <div className="blog">
                            {this.displayBlogPost(this.state.posts)}
                        </div>                   
                        </Container>
                    </div>

                );
            }

    }

【问题讨论】:

  • 如果您的大部分组件在 xhr 之后呈现在客户端上,那么使用 nextjs 毫无意义。也许 nextjs 的 getInitialProps 可以帮助你。
  • 为了实现这一点,我可以对代码进行哪些更改? @HMR
  • 我检查了 getInitialProp 但它只接受 https 获取。我可以对代码进行哪些更改以根据他们的 ID 获取帖子正文、标题? @HMR
  • 您可以从在任何地方实际渲染 PostsLists 组件开始。
  • 我没听懂你。 @HMR。我能够呈现我的帖子列表(博客).. 我希望当有人点击我博客的标题时,它会转到一个新页面并根据其 ID 显示标题和正文

标签: reactjs mongodb typescript next.js


【解决方案1】:

首先你应该创建帖子route

pages/post/index.js

import React from 'react'

class Post extends React.Component {
  static async getInitialProps({ query }) {
    return { query };
  }

  render() {
    return <div>id: {this.props.query.id}</div>
  }
}

export default Post

然后创建 pages/post/[id].js

import Post from './index'
export default Post

现在,当您打开 localhost:port/post/22localhost:port/post?id=22 时,它应该会显示数字 22。

要链接到另一个页面的帖子,您可以创建以下链接:

<Link href={`/post?id=${id}`} as={`/post/${id}`}>
  <a>{title}</a>
</Link>

如果这仍然不起作用,请向我们展示代码(在 github 上)。

如果它有效,那么现在您可以将 id 传递给帖子页面,因此您只需要获取帖子。您可以在getInitialProps 中做到这一点

class Post extends React.Component {
  static async getInitialProps({query}) {
    const post = await axios.get(url, { // make sure the url is full url, no relative urls
      params: {
        id: query.id
      }
    })
    return { post: post.data }
  }

  render() {
    return (
      <pre>
        post:{' '}
        {JSON.stringify(this.props.post, undefined, 2)}
      </pre>
    )
  }
}

【讨论】:

  • 除了最后一步之外,所有步骤都可以正常工作,我必须粘贴 URL 的代码,我已粘贴:localhost:8080/api 在 url 部分,如 const post = await axios.get('@ 987654323@' 。这似乎呈现了我所有的帖子,而不是呈现该特定帖子的标题和正文
  • @Rebel 好的,现在你可以试试这个:If that still doesn't work then please show us the code (on github). 没有它,任何人都可以猜测代码还有什么问题。
  • 我已经在上面的代码中添加了我所有的 3 个文件(更新的代码)。实际上没有比这 3 个文件更多的文件了
  • 所以即使我上传了代码,也只是上面粘贴了代码的这3个文件。 @HMR。但我可以完成所有步骤。只是最后一个文件似乎有问题
  • @Rebel 这是working example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 2022-07-15
  • 2011-05-30
  • 2021-09-23
  • 1970-01-01
  • 2022-12-23
相关资源
最近更新 更多