美文网首页
React开发之【Mobx状态管理,非装饰器模式】

React开发之【Mobx状态管理,非装饰器模式】

作者: Hamiltonian | 来源:发表于2022-12-13 11:00 被阅读0次

    React开发之【Mobx状态管理,非装饰器模式】

    React项目装饰器开启失败, 下面是不用装饰器模式的写法

    A.【Store.js】存放状态所有需要数据驱动的状态

    import { observable, computed} from "mobx";
    const store = observable({
        price:1,
        amount:1,
        total:1,
    });
    export default store
    

    B.【Test.js】和Store.js绑定的UI:(全部需要数据UI驱动的变量都要在autorun里面)

    import React from 'react';
    import {autorun, observer} from 'mobx';
    import store from './Store';
    class Test extends React.Component{
         
        constructor() {
            super();
    
            this.addPrice = this.addPrice.bind(this);
            this.addAmount = this.addAmount.bind(this);
          }
          componentDidMount(){
            autorun(()=>{
              ///全部需要数据UI驱动的变量都log在这里
              console.log(store.price);
              console.log(store.amount);
              console.log(store.total);
              this.setState({});
            });
            // this.addPrice = this.addAmount.bind(this);
            // this.addAmount = this.addAmount.bind(this);
          }
    
          addPrice(){
            store.price = store.price+1;
            store.total = store.amount * store.price;
    
          }
    
          addAmount(){
            store.amount = store.amount+1;
            store.total = store.amount * store.price;
     
          }
          render(){
            return(
                <div>
                <h1>Hello, world!</h1>
                <h2 onClick={this.addPrice}>price++ {store.price}</h2>
                <h2 onClick={this.addAmount}>amount++ {store.amount}</h2>
                <h2 >total {store.total}</h2>
              </div>
            )
          }
    }
    
    export default Test;
    

    C.【index.js】调用TestWidget

    import Test from './Test'
    
     <div>
      <Test></Test>
      <Test></Test>
      <Test></Test>
    </div>
    

    D.<Observer> 组件用法还没搞明白【特此记录一下,大神请说下它的用法】

    import {Observer} from "mobx-react"
    <Observer>
    {
      ()=>{
           console.log(store.amount);
          return <div>
            <Test price={store.price} amount={store.amount} total={store.total}></Test>
            <Test price={store.price} amount={store.amount} total={store.total}></Test>
            
          </div>
    
      }
    }
    </Observer>
    

    相关文章

      网友评论

          本文标题:React开发之【Mobx状态管理,非装饰器模式】

          本文链接:https://www.haomeiwen.com/subject/uljhqdtx.html