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

关于mobx中的@computed配和get可加可不加的问题 #90

Open
ckinmind opened this issue Mar 5, 2017 · 2 comments
Open

关于mobx中的@computed配和get可加可不加的问题 #90

ckinmind opened this issue Mar 5, 2017 · 2 comments
Labels

Comments

@ckinmind
Copy link
Owner

ckinmind commented Mar 5, 2017

在看mobx api @computed中提到不加@computed等同于加了@computed,自己测试过程也是如此,代码如下

export default class TodoStore {
	@observable todos = [];
        @computed get activeTodoCount() {
		return this.todos.reduce(function(sum, todo){
		   return sum + (todo.completed ? 0 : 1)
		}, 0);
	}
}
  1. 测试过程发现加不加@computed ,都可以获取正确的activeTodoCount的值
  2. get的用法是ES6的用法,用于拦截(修改)该属性的存取行为,就是在存取之前再对值做一次处理
  3. @compute的作用根据文档得知:计算属性就是那些基于状态或者其他计算属性运算而来的值
@ckinmind ckinmind added the mobx label Mar 5, 2017
@ckinmind
Copy link
Owner Author

ckinmind commented Mar 5, 2017

参考资料:MobX中@computed和自定义get函数的区别

  1. 首先这两者解决方法都会得到一个相同的结果,但使用@computed的意义在于它能够由MobX进行更智能的优化。
  2. 如果我不使用computed属性,直接使用自定义的getTheValue函数的话,那么只要value改变,所有用到getTheValue函数的地方都将重新计算。
  3. 如果使用了@computed get getValue,那么getValue将会被缓存,如果value没有改变,那么getValue也不会改变,其它组件也不会收到通知。
  4. 此外如果你读取getValue的值,你通常会得到一个缓存的值,而不带@computed装饰器,则会重新计算……

参考资料:What's difference between @computed decorator and getter function

@geograous
Copy link

good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants