【问题标题】:Converting React Typescript application to Nextjs将 React Typescript 应用程序转换为 Nextjs
【发布时间】:2020-05-28 13:15:24
【问题描述】:

我是 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

【问题讨论】:

    标签: reactjs typescript next.js


    【解决方案1】:

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

    例如。

    pages/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>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2017-01-04
      • 2016-07-16
      • 2023-02-09
      • 2021-04-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多