Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[讨论] - 关于页面初始数据依赖的声明问题 #1402

Closed
kpaxqin opened this issue Dec 17, 2017 · 3 comments
Closed

[讨论] - 关于页面初始数据依赖的声明问题 #1402

kpaxqin opened this issue Dec 17, 2017 · 3 comments

Comments

@kpaxqin
Copy link

kpaxqin commented Dec 17, 2017

官方文档 和 hackernews示例中,都使用了在model的subscription中监听匹配history url的方式为页面加载初始数据,如下。

//摘自api文档
app.model({
  namespace: 'todo',
  // ... 
  subscriptions: {
    setup({ history, dispatch }) {
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({ type: 'load' });
        }
      });
    },
  },
});

传送门:类似写法的 dva-hackernews的item model

这与通常见到的在页面组件的生命周期加载数据有所不同,比如同样是hakernews的例子,我们可以选择在ListPage 的componentWillMount或componentDidMount去dispatch 相应的effects action做请求,甚至从server render的角度思考,可以添加额外的生命周期(比如next.js的getInitProps)来负责声明这种页面的初始数据依赖。

目前把页面的初始数据依赖放到model的subcription中的方式,个人存在以下疑问:

  1. url match逻辑重复: 解析url参数并转发到业务逻辑是router的职责,从hackernews的例子能看出来 已经 有一部分重复了,甚至会用到pathToRegex这样相对“底层”的库(react-router/express背后也是用的它做url匹配和解析)
  2. 职责分离:不同的做法对应不同的语义,是由页面声明该页依赖哪些数据,还是由model声明在什么url下执行数据加载?
  3. 页面失去了对请求的控制权,如果某个页面想在请求成功或失败后执行特定的逻辑,会比较难实现 ,因为页面本身对加载数据这个动作是没有感知的
  4. 如何应对server render/isomorphic场景,其实是3的延续,在server render下,需要“先加载页面依赖的数据,再执行页面渲染”,而如果对请求的声明根本不在页面级,要做到这事就比较麻烦了
  5. subscription的设计似乎是受elm的影响,但是在elm中subscription的使用其实也并不多,只是用来对付websocket等场景,初始请求还是通过页面声明init做的。

当然,dva并没有限制采用哪种方式,在dva中使用页面组件生命周期的做法是完全可行的,只是我觉得具有示范作用的官方文档和示例都用了另一种做法,很可能还有我不知道的考量,之前也加了微信群提问,但没能得到答案(有朋友说是因为dva希望页面组件也是functional component,确实是一个点,但似乎没有那么强的说服力),因此开issue叨扰,见谅。
@sorrycc

@kpaxqin kpaxqin changed the title [讨论] - 关于页面数据依赖的问题 [讨论] - 关于页面初始数据依赖的声明问题 Dec 17, 2017
@yangbin1994
Copy link
Contributor

yangbin1994 commented Dec 18, 2017 via email

@kpaxqin
Copy link
Author

kpaxqin commented Dec 18, 2017

@yangbin1994

model的inithook指的是?
我在model文档里没看到呢。

假设有这个Hook,其实和在subscription中做似乎也没有本质上的不同,上述1-4点疑问仍然存在

@sorrycc sorrycc closed this as completed Apr 18, 2018
@sorrycc sorrycc reopened this Apr 18, 2018
@stale
Copy link

stale bot commented Mar 14, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix label Mar 14, 2019
@stale stale bot closed this as completed Mar 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants