拆分各页面state

在src下创建mobx文件夹
mobx内目录如下
image.png
index.js为mobx的入口文件,主要做一些mobx配置等,仓库合并抛出,我在index.js里,用了require.context
方法,读取modules下的js文件,转化为对象抛出。

mobx/index.js

  1. const modelCreator = function () {
  2. const store = {};
  3. const context = require.context('./modules', false, /\.(js|ts)$/);
  4. const modelList = context.keys();
  5. modelList.forEach((model) => {
  6. const newSpaces = model.match(/\/(\w+)\.js$/)[1];
  7. store[newSpaces] = context(model).default;
  8. });
  9. return store;
  10. };
  11. export default modelCreator();

在modules/detail.js

  1. import { observable, action, makeAutoObservable } from 'mobx';
  2. import api from '../../api'; //引入api
  3. import { message } from 'antd'; //全局提示
  4. let { detail } = api; //解构出来detail的api请求
  5. //拆分了UIStore,管理当前页所有的ui数据
  6. class UIStore {
  7. @observable x = 0;
  8. @action setX = () => this.x++;
  9. }
  10. //拆分了DomainStore,管理当前页的数据
  11. class DomainStore {
  12. @observable titleList = [];
  13. @observable essayObj = {};
  14. @action getTitleList = async () => {
  15. let { data } = await detail._getList();
  16. if (data.code === 200) {
  17. this.titleList = data.data;
  18. // message.success(data.msg);
  19. } else {
  20. console.log(data.data);
  21. message.error(data.msg);
  22. }
  23. }
  24. @action getEssayObj = async (obj) => {
  25. let { data } = await detail._getListObj({ params: obj });
  26. if (data.code === 200) {
  27. this.essayObj = data.data;
  28. // message.success(data.msg);
  29. } else {
  30. console.log(data.data);
  31. message.error(data.msg);
  32. }
  33. }
  34. }
  35. //合并UIStore和DomainStore
  36. class Store {
  37. @observable uiStore = new UIStore();
  38. @observable domainStore = new DomainStore();
  39. }
  40. export default makeAutoObservable(new Store());

detail页面使用mobx

  1. import React, { Component } from 'react';
  2. import { inject,observer } from 'mobx-react';
  3. import './detail.scss';
  4. import { BankOutlined } from '@ant-design/icons';
  5. import {Link} from 'react-router-dom';
  6. @inject('detail')
  7. @observer
  8. class Detail extends Component {
  9. state = {
  10. id: "",
  11. leftList: [],
  12. essayObj: {}
  13. }
  14. componentDidMount() {
  15. this.init();
  16. }
  17. async init() {
  18. let id = this.props.location.state?.id?this.props.location.state.id:'1';
  19. let { domainStore } = this.props.detail;
  20. await domainStore.getTitleList();
  21. await domainStore.getEssayObj({id});
  22. let {titleList,essayObj} = domainStore;
  23. this.setState({
  24. id,
  25. essayObj,
  26. leftList: titleList
  27. });
  28. }
  29. changeId = async (id) => {
  30. let { domainStore } = this.props.detail;
  31. await domainStore.getEssayObj({id});
  32. let {essayObj} = domainStore;
  33. this.setState({
  34. id,
  35. essayObj
  36. })
  37. }
  38. render() {
  39. let { id, essayObj, leftList } = this.state;
  40. return (
  41. <div className="detaill">
  42. <div className="detaill_header">
  43. <BankOutlined />
  44. <Link to="/"><span className="navItem">Home</span></Link>/
  45. <span className="navItem">detaill</span>/
  46. <span className="navItem">{id}</span>
  47. </div>
  48. <div className="detaill_main">
  49. <div className="detaill_left">
  50. <div className="detaill_left_top">
  51. 目&emsp;录
  52. </div>
  53. <div className="detaill_left_certer">
  54. <ul>
  55. {
  56. leftList[0] && leftList.map(item => (
  57. <li
  58. onClick={() => this.changeId(item.id)}
  59. className={item.id === id ? 'active' : ''}
  60. key={item.id}
  61. >
  62. {item.title}
  63. </li>
  64. ))
  65. }
  66. </ul>
  67. </div>
  68. <div className="detaill_left_bottom"></div>
  69. </div>
  70. <div className="detaill_center">
  71. {
  72. essayObj.id && (<div ref={c => this.center = c}>
  73. <div className="detaill_main_title">
  74. <div className="title">{essayObj.title}</div>
  75. <div className="type">{essayObj.className}</div>
  76. </div>
  77. <div className="detaill_main_content">
  78. <div className="_html" dangerouslySetInnerHTML={{ __html: essayObj.conText }} />
  79. </div>
  80. <div className="img">
  81. <img src={essayObj.img} alt="" />
  82. </div>
  83. <div className="detaill_main_time">
  84. {essayObj.dataTime}
  85. </div>
  86. </div>)
  87. }
  88. <div className="detaill_main_bottom">
  89. </div>
  90. </div>
  91. <div className="detaill_right">
  92. </div>
  93. </div>
  94. <div className="detaill_footer">
  95. </div>
  96. </div>
  97. )
  98. }
  99. }
  100. export default Detail;

注意注意,最外层引入mobx

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import './index.css';
  4. import App from './App';
  5. import reportWebVitals from './reportWebVitals';
  6. import store from './mobx';
  7. import {Provider} from 'mobx-react';
  8. ReactDOM.render(
  9. <Provider {...store}>
  10. <App />
  11. </Provider>,
  12. document.getElementById('root')
  13. );
  14. // If you want to start measuring performance in your app, pass a function
  15. // to log results (for example: reportWebVitals(console.log))
  16. // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
  17. reportWebVitals();