本人笔记地址分享:全部笔记

#目录

Mobx使用与安装

一、安装

默认安装最新版,目前这是mobx6,这个版本中默认不支持装饰器了

  1. 安装: npm install mobx --save React 绑定库: npm install mobx-react --save

这是mobx5安装,这版本默认支持装饰器 (在umi等框架中可能会出现问题,具体解决见踩坑部分的题解决)

  1. npm i mobx@5.15.7 mobx-react@6.2.5

二、react中使用Mobx

①、使用两个babel插件

  1. babel/plugin-proposal-decorators
  2. babel/plugin-proposal-class-properties

②、package.json中的ESLint配置与babel配置

  1. "parserOptions": {
  2. "ecmaFeatures": { "lengacyDecorators": true} //开启检查处理
  3. },

③、package.json改动的配置

  1. //package.json
  2. "eslintConfig": {
  3. "parserOptions": {
  4. "ecmaFeatures": {
  5. "lengacyDecorators": true
  6. }
  7. },
  8. "extends": [
  9. "react-app",
  10. "react-app/jest"
  11. ]
  12. },
  13. "babel": {
  14. "plugins": [
  15. ["@babel/plugin-proposal-decorators",
  16. {
  17. "legacy": true
  18. }],
  19. [
  20. "@babel/plugin-proposal-class-properties",
  21. {
  22. "loose":true
  23. }
  24. ]
  25. ],
  26. "presets": [
  27. "react-app"
  28. ]
  29. },

踩坑与解决

问题一、使用@action后数据已经改变,但是页面并没有渲染

在新版本中提供了以下的方法

  1. class AppStore {
  2. @observable time = "2019年";
  3. @observable todos:string[] = ["xxx"]
  4. @action addTodo=(todo:string)=> {
  5. this.todos.push(todo)
  6. }
  7. @action deleteTodo() {
  8. this.todos.pop()
  9. }
  10. @action resetTodo() {
  11. this.todos=[]
  12. }
  13. }
  14. const store = new AppStore()
  15. //监听
  16. makeAutoObservable(store)
  17. export default store

问题二、声明的computed调用报错

报错Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

  1. @computed getdesc(){//错误的
  2. return `${this.time} 还有${this.todos.length}条未完成`
  3. }
  4. @computed get getdesc(){//正确的 需要加get定义
  5. return `${this.time} 还有${this.todos.length}条未完成`
  6. }

问题三、ts报错

Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators'option in your ‘tsconfig’ or ‘jsconfig’ to remove this warning.

很明显 直接按照报错提示去ts配置文件加一段配置

  1. "compilerOptions": {
  2. ...
  3. "experimentalDecorators":true,
  4. ...
  5. }

问题四、使用mobx5版本出错

“export ‘observerBatchingOptOut’ was not found in ‘mobx-react-lite’

yarn start后报错 这里怀疑是版本问题

解决:

删除整个node_modules文件,并检查package.json文件中的版本,确定版本中有^,没有的话加上去,刚开始我就是没有,导致重新安装依赖后仍然报错

  1. "mobx": "^5.15.7",
  2. "mobx-react": "^6.2.5",