• mobx-react


    npx create-react-app hello-mobx
    yarn add mobx mobx-react react-router-dom

    使用装饰器

    https://www.jianshu.com/p/2e23781c957f

    新建文件夹store

    新建文件 homeStore.js index.js oneStore.js

    homeStore.js

    import { observable} from "mobx";
    class HomeStore {
      @observable homeNum = 0;
    }
    export default HomeStore;

    oneStore.js

    import { observable} from "mobx";
    class OneStore {
      @observable oneNum = 3333;
    }
    export default OneStore;

    index.js

    import HomeStore from "./homeStore";
    import OneStore from "./oneStore";
    let oneStore = new OneStore();
    let homeStore = new HomeStore();
    const stores = {
      oneStore,
      homeStore
    };
    /// 默认导出接口
    export default stores;

    index.js 主入口

    import React from "react";
    import ReactDOM from "react-dom";
    import Router from "./router/router";
    import { Provider } from "mobx-react";
    import stores from "./store";
    ReactDOM.render(
      <Provider {...stores}>
        <Router />
      </Provider>,
      document.getElementById("root")
    );

    home.jsx页面

    import React, { Component } from "react";
    + import { observer, inject } from "mobx-react";
    + @inject("homeStore")
    + @observer
    class Home extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
      render() {
        return (
          <div>
           +  <h1>首页数据源的number为:{this.props.homeStore.homeNum}</h1>
            <button onClick={() => {  this.props.history.push("/one") }}> 
                跳转到第一个页面
            </button>
          </div>
        );
      }
    }
    export default Home;

    修改数据源

    //homeStore.js
    import { observable,action} from "mobx";
    class HomeStore {
      @observable homeNum = 0;
      + @action addNum() {
      +  this.homeNum += 1;
      + }
      + @action lessNum() {
      +  this.homeNum -= 1;
      + }
    }
    export default HomeStore;
      render() {
        return (
              //代码自行添加。。。。。。
        +  <div>
        +   <h1>首页数据源的number为:{this.props.homeStore.homeNum}</h1>
        +    <button onClick={() => {this.props.homeStore.addNum()}} >
        +      点击添加
        +    </button>
        +    <button  onClick={() => {this.props.homeStore.lessNum()}}>
        +     点击删除
        +    </button>
        +  </div>
        //代码自行添加。。。。。。
        );
      }
    }
    export default Home;
  • 相关阅读:
    计算与软件工程作业四
    计算与软件工程作业四(一)
    计算与软件工程作业三
    计算与软件工程作业二
    计算与软件工程作业一
    4.2上机课作业
    java第三次作业
    java第一次作业 2020 3.7
    十三周上机练习
    第十二周作业
  • 原文地址:https://www.cnblogs.com/lxz-blogs/p/13559523.html
Copyright © 2020-2023  润新知