如何/在哪里将模型/控制器放在下一个 js 应用程序中?

arv*_*rve 4 reactjs next.js

使用 next.js 学习 javascript 开发。我创建了一个框架项目,其结构如下。什么是最好的发展方式。创建模型、控制器?模型和控制器文件夹应该在哪里?或者在反应世界中有不同的方法来做到这一点?

app
> .next
> node_modules
> pages
  > api
    > app.js
> public
> src
Run Code Online (Sandbox Code Playgroud)

Vic*_*eig 12

TL;DR 由于 nextjs 在此级别不强加约定,因此完全由您和您的团队决定采用哪种架构以及如何实现和组织它。您可以从类似 MVC 的框架(例如https://blitzjs.com/)中汲取灵感中汲取灵感,该框架成功地从现在陈旧乏味的 Ruby on Rails 中引入了许多概念。

\n

如果你仔细想想,服务器端的MVC与 nextjs 非常契合。这就是我从经典的模型-视图-控制器角度看待它的方式:

\n

控制器根据用户交互操作您的模型,将结果拼接在一起并将它们传递到视图。

\n

用 nextjs 的话来说,pages确实非常适合这个职责,尽管他们做的远不止于此。您可以将模型放在任何您想要的位置,许多入门级教程将它们放在lib/.

\n

考虑这个例子,我有一个页面来显示用户个人资料,在这种情况下,我也对静态站点生成感兴趣。旁注,我是凭空写下这个的,所以要注意复制和粘贴来运行它,它很可能不起作用。

\n
// under app/pages/users/[userId].js\n\nimport UserProfile from \'components/user-profile\';\nimport User from \'models/user\';\n\nexport default UserProfile;\n\n// both at request time and build time, preps the props passed to the View.\nexport const getStaticProps = async ({params}) => {\n  const user = await User.find(params.id);\n  return { \n    props: { user }\n  }\n}\n\n// instructs next to render all user profiles using SSG\nexport const getStaticPaths = async () => {\n  const users = await User.findAll();\n  const paths = users.map(user => `/users/${user.id}`);\n  return { paths, fallback: false }; \n}\n
Run Code Online (Sandbox Code Playgroud)\n

我和我的团队喜欢更进一步,并遵循这种结构,尽管我们不与数据库交互,而是通过 REST 和 GraphQL 交互文件系统和一些第三方 API。小秘密:我们告诉 nextjs要查找哪些文件来加载页面,否则会有点疯狂。

\n
project\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 app\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 components\n    \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 user-profile.test.tsx\n    \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 user-profile.tsx\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 models\n    \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 user.ts\n    \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 user.test.ts\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 pages\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 users\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 [userId].page.ts\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 get-static-paths.test.ts\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 get-static-paths.ts\n            \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 get-static-props.test.ts\n            \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 get-static-props.ts\n
Run Code Online (Sandbox Code Playgroud)\n