首页 > 解决方案 > 将 React Typescript 应用程序转换为 Nextjs

问题描述

我是 Nextjs 的新手,我已经使用 Reactjs + Typescript 构建了一个 Web 应用程序,我想将其转换为 Nextjs。我对去哪里和安装部分的文件结构感到困惑。当前的 Web 应用程序(带有 Typescript 的 Reactjs)有一个数据库(Postdb)和如下功能:

  1. 创建新笔记
  2. 评论笔记
  3. 喜欢和不喜欢这张纸条。

有没有办法可以将这个现有项目顺利转换为 nextjs?

这也是我的文件结构


(New-App)
 * node_modules
 * public
   * index.html
   * manifest.json
   * robots.txt
 * src
   * App.tsx
   * db.tsx
   * serviceWorker.ts
   * index.tsx
   * components
       *Notes.tsx
       *Header.tsx
       *List.tsx

   *pages
       *index.tsx
       *Quest.tsx
       *Page.tsx

    * test (has all the test files)
    * images

 *build

标签: reactjstypescriptnext.js

解决方案


Nextjs 的 pages 目录与 route 相关联(参见此链接),最好将 SSR 逻辑从每个 react 组件中分离出来。
所以我更喜欢页面文件有路由和 SSR 逻辑,组件文件有模板和客户端逻辑。

例如。

页面/index.tsx

import Notes from '../components/notes'
function HomePage({ notes }) {
  return (
    <div>
      <Notes notes={notes}></Notes>
    </div>
  )
}

HomePage.getInitialProps = async ({ req }) => {
  // DO SSR
  const res = await fetch('https://some/api/endpoint')
  const json = await res.json()
  return { notes: json.notes }
}

export default HomePage

组件/注释/index.tsx

import Note from './Note';
export default (props) => {
  return (
    <div>
    {
      props.notes && props.notes.map((note) => <Note note={note}></Note>)
    }
    </div>
  )
}

组件/注释/Note.tsx

export default (props) => {
  return (
    <div>
      <p>comment {props.note.comment}</p>
      <p>like {props.note.like}</p>
      <p>dislike {props.note.dislike}</p>
    </div>
  )
}

推荐阅读