react mobx状态管理

//list.js
const { Button } = WeaverMobile;
const { TabBar, Icon,Tabs, WhiteSpace, Badge ,Accordion, List} = WeaverMobile;
const { Provider,inject,observer } = mobxReact;
const { NavBar } = WeaverMobile;
const { Carousel, WingBlank } = WeaverMobile;
const {toJS} = mobx;

const tabs2 = [
  { title: 'First Tab1221', sub: '1' },
  { title: 'Second Tab', sub: '2' },
  { title: 'Third Tab', sub: '3' },
];
//react组件层,用来定义视图和交互
//inject获取baseFormStore到组件props中
//observer来支持集成mobx
@inject("homeStore")
@observer
class ListComponent extends React.Component {
  constructor(props) { //初始化,固定语法
    super(props);
      this.state = {
      selectedTab: 'redTab',
      hidden: false,
      fullScreen: false,

      data: ['1', '2', '3'],
      imgHeight: 130,
    };
  }
  componentDidMount() {
    // console.log('componentDidMount()')
    const { homeStore }=this.props;

      // window.onload = function(){
      //   var box=document.getElementById("test");
      //     if(box){ //此处在加一层判断,更加严密,如果box存在的情况下获取
      //       console.log(box.offsetHeight)
      //       if(box.offsetHeight > 75){//超过3行
      //         homeStore.setScaleCollpased(true) ;
      //         homeStore.setsSaleNeedCollpased(true) ;
      //       }
      //     }
      // }

  }

  componentDidUpadte(){
    // console.log('componentDidUpadte()')
  }

  componentWillMount(){ 
    if(Tools.mobileDetect().is('iPhone')&&window.iNoBounce&&window.iNoBounce.isEnabled()){ 
      window.iNoBounce.disable(); 
    } 
    // console.log('componentWillMount()')
  } 

  componentWillUnmount() { 
    if(Tools.mobileDetect().is('iPhone')&&window.iNoBounce&&window.iNoBounce.isEnabled()){ 
      window.iNoBounce.enable(); 
    } 
  }


  onChange = (key) => {
    // console.log(key);
  }

  scaleExpand = () =>{
    const { homeStore } = this.props; //获取store
    const {scaleCollpased} = homeStore;
    
    homeStore.setScaleCollpased(!scaleCollpased) ;

  }

  scaleSpan = () =>{
    const { homeStore } = this.props; //获取store
    let {previousInfo, scaleCollpased, scaleNeedCollpased} = homeStore;
    // console.log('scaleCollpased:' + scaleCollpased +', scaleNeedCollpased:' + scaleNeedCollpased);
    // console.log(previousInfo.scale);
 
    let _scale = '';
    if(previousInfo.scale != undefined && previousInfo.scale.length > 45 && scaleNeedCollpased == false){
      // console.log(previousInfo.scale.length);
      homeStore.setScaleCollpased(true) ;
      homeStore.setsSaleNeedCollpased(true);
          // console.log('111111111')
    }

    if(previousInfo.scale != undefined && previousInfo.scale == ''){
      scaleCollpased = false;
      scaleNeedCollpased = false;
    }
    // else{
    //   homeStore.setScaleCollpased(false) ;
    //   homeStore.setsSaleNeedCollpased(false);
    //       console.log('222222222222222222222')
    // }

    if(scaleCollpased){
      _scale = previousInfo.scale.substring(0,45) + '...'
    }else{
      _scale = previousInfo.scale
    }

    // console.log(_scale)

    

    // var box=document.getElementById("test");
    // if(box){ //此处在加一层判断,更加严密,如果box存在的情况下获取
    //   console.log(box.offsetHeight)
    //     if(box.offsetHeight > 75){//超过3行
    //     homeStore.setScaleCollpased(true) ;
    //     homeStore.setsSaleNeedCollpased(true) ;
    //   }
    // }

    

      return(
        <div><span  className='left-span'>建设规模</span>
          <span ref = {() => {}} className='right-span'>{_scale}<span onClick={this.scaleExpand} style={{display:scaleNeedCollpased?'block':'none',color:'#036DD7'}}>{scaleCollpased?'展开':'收起'}</span></span>
        </div>
      )

    


  }


  render() { //渲染
    const { homeStore } = this.props; //获取store
    const { hidden } = this.state; //获取store
    const {previousInfo} = homeStore;
    if(previousInfo == undefined || previousInfo == null){
      return alert('没有数据');
    }

    let telInfo = 'tel:'+ previousInfo.contactMobile;
    let leadTelInfo = 'tel:'+ previousInfo.leaderMobile;
    // console.log(telInfo)


    //    console.log('render()')
     return (
       
      <div>
       <div>
       <div>
                <Accordion openAnimation={{}} defaultActiveKey={['1','2']} className="my-accordion" onChange={this.onChange}>
                  <Accordion.Panel className="panel"  header="项目基本信息" key={'1'}>
                    <List className="my-list">
                      <List.Item>
                        <div><span className='left-span'>项目名称</span><span  className='right-span'>{previousInfo.projectName}</span></div>
                      </List.Item>
                      <List.Item multipleLine wrap>
                         {/**<div><span  className='left-span'>建设规模</span><span id='test' ref = {() => { console.log('*********')}} className='right-span'>{previousInfo.scale}</span></div> */}
                         {this.scaleSpan()}
                      </List.Item>
                       <List.Item>
                        <div><span className='left-span'>总投资</span><span  className='right-span'>{(Number(previousInfo.planTotalFund)/10000).toFixed(2)}亿元</span></div>
                      </List.Item>
                      <List.Item>
                        <div><span className='left-span'>计划年份</span><span  className='right-span'>{previousInfo.planStartYear}</span></div>
                      </List.Item>
                    </List>
                  </Accordion.Panel>
                  <Accordion.Panel className="panel"  header="责任单位" key={'2'}>
                    <List className="my-list">
                      <List.Item>
                        <div><span className='left-span'>单位名称</span><span  className='right-span'>{previousInfo.unitName}</span></div>
                      </List.Item>
                      <List.Item>
                         <div><span className='left-span'>责任领导</span><span  className='right-span'>{previousInfo.leader}</span></div>
                      </List.Item>
                       <List.Item>
                        <div><span className='left-span'>责任领导电话</span><span  className='right-span tel-num'><img src="${appRes}/tel-icon.png"/>{previousInfo.leaderMobile}<a style={{display:(previousInfo.leaderMobile == '' || previousInfo.leaderMobile == 'undefined')?'none':''}} href={leadTelInfo}>点击拨号 ></a></span></div>
                      </List.Item>
                       <List.Item>
                        <div><span className='left-span'>联系人</span><span  className='right-span'>{previousInfo.contacts}</span></div>
                      </List.Item>
                       <List.Item>
                        <div>
                          <span className='left-span'>联系人电话</span><span  className='right-span tel-num'><img src="${appRes}/tel-icon.png"/>{previousInfo.contactMobile}<a style={{display:(previousInfo.contactMobile == '' || previousInfo.contactMobile == 'undefined')?'none':''}} href={telInfo}>点击拨号 ></a></span>
                        </div>
                      </List.Item>
                    </List>
                  </Accordion.Panel>
                </Accordion>
        </div>
       </div>
      </div>

     )
  }
}

ecodeSDK.exp(ListComponent);

//mobx store状态管理

const {observable,action} = mobx;
const { RouteLayout } = WeaverMobilePage;
class HomeStore { //store层,用来定义和处理前端纯数据
  @observable previousInfo = {};
  @observable progressInfo = {};
  @observable projectId = 'test0000001';
  @observable scaleCollpased = false;//建设规模是否收起
  @observable scaleNeedCollpased = false;//建设规模是否收起
  @observable oneWordCollpased = false;//建设规模是否收起
  @observable oneWordNeedCollpased = false;//建设规模是否收起
  @observable preProgress = [];//建设规模是否收起

  @action
  getPreviousInfo = (param) => {
    // console.log('getPreviousInfo');
    API.getPreviousInfo(param).then(action(res => {
      // console.log('getPreviousInfo');
      if (res.api_status) { // 接口请求成功/失败处理
        this.scaleCollpased = false; //初始化
        this.scaleNeedCollpased = false;//初始化
        this.previousInfo = res.data;
      } else {
        message.error(res.msg || 'getPreviousInfo 接口调用失败!')
      }
    }));
  }

  @action
  getProgress = (param) => {
    // console.log('getProgress');
    API.getProgress(param).then(action(res => {
      // console.log('getProgress');
      if (res.api_status) { // 接口请求成功/失败处理
        this.oneWordCollpased = false;
        this.oneWordNeedCollpased = false;
        this.progressInfo = res.data;
      } else {
        message.error(res.msg || 'getProgress 接口调用失败!')
      }
    }));
  }

  @action
  getPreProgress = (param) => {
    API.preProgress(param).then(action(res => {
      if (res.api_status) {//preProgress
        let rdd = res.data;
        var table = [];
        if(rdd == undefined) {
          this.preProgress = [];
          return;
        }
        table.push({name:"红线用地(亩)",pre:rdd.preHxyd,act:rdd.actHxyd,rate:rdd.hxydRate});
        table.push({name:"大临用地(亩)",pre:rdd.preDlyd,act:rdd.actDlyd,rate:rdd.dlydRate});
        table.push({name:"民房拆迁(㎡)",pre:rdd.preMfcq,act:rdd.actMfcq,rate:rdd.mfcqRate});
        table.push({name:"厂房拆迁(㎡)",pre:rdd.preCfcq,act:rdd.actCfcq,rate:rdd.cfcqRate});
        table.push({name:"坟墓迁移(处)",pre:rdd.preFmcq,act:rdd.actFmcq,rate:rdd.fmcqRate});
        table.push({name:"110KV及以上电力迁改(处)",pre:rdd.preDlqg,act:rdd.actDlqg,rate:rdd.dlqgRate});
        table.push({name:"通讯线路迁改(处)",pre:rdd.preTxxl,act:rdd.actTxxl,rate:rdd.txxlRate});
        table.push({name:"给排水管线迁改(处)",pre:rdd.preGpsg,act:rdd.actGpsg,rate:rdd.gpsgRate});
        table.push({name:"油气管线迁改(处)",pre:rdd.preYqgx,act:rdd.actYqgx,rate:rdd.yqgxRate});
        this.preProgress = table;
      } else {
        message.error(res.msg || 'preProgress 接口调用失败!')
      }
    }));
  }

  @action
  setProjectId = (param) => {
    this.projectId = param;
  }

  @action
  setScaleCollpased = (param) => {
    this.scaleCollpased = param;
  }  
  
  @action
  setsSaleNeedCollpased = (param) => {
    this.scaleNeedCollpased = param;
  }

  @action
  setOneWordCollpased = (param) => {
    this.oneWordCollpased = param;
  }  
  
  @action
  setOneWordNeedCollpased = (param) => {
    this.oneWordNeedCollpased = param;
  }
}
ecodeSDK.exp(HomeStore);





//api.js接口封装

const { Tools } = WeaverMobile;
ecodeSDK.imp(ThreeBattleMobileAjax)

const getPreviousInfo = params => {
    options={
    url:'/api/detail/getPreviousInfo',
    method:'GET',
    params
  }  
  return ThreeBattleMobileAjax.callApi(options);
};

const getProgress = params => {
    options={
    url:'/api/detail/getProgress',
    method:'GET',
    params
  }  
  return ThreeBattleMobileAjax.callApi(options);
};
const preProgress = params => {
    options={
    url:'/api/projectItem/preProgress',
    method:'GET',
    params
  }  
  return ThreeBattleMobileAjax.callApi(options);
};

const API = {
  getPreviousInfo,
  getProgress,
  preProgress
}


ecodeSDK.exp(API);

//ajax.js请求
const server = 'https://mobile.cncico.com:9453'
// const server = 'http://10.100.218.8'
var fetchOld = window.fetch;
var fetchnew = function (options){
  let userId = localStorage.getItem("userId");
  let loginId = localStorage.getItem("loginId");
  // options.headers = options.headers
  if(options.method == 'GET'){
    // return fetchOld(server + options.url + jasonToString(options.params),{
    //   method: 'get',
    //   headers: {
    //     'userId':userId
    //   }
    // })
    return new Promise((resolve, reject) => {
      if (window.XMLHttpRequest)
      {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xhr=new XMLHttpRequest();
      }
      else
      {
        // IE6, IE5 浏览器执行代码
        xhr=new ActiveXObject("Microsoft.XMLHTTP");
      }
 
      xhr.onload = () => {
          if(xhr.readyState==4 && xhr.status==200){
            resolve(xhr.response);
          }
        };
             
            xhr.open('GET', server + options.url + jasonToString(options.params), false);
            xhr.setRequestHeader('userId', userId);// 设置content-type
            // xhr.setRequestHeader('userPhone', loginId);// 设置content-type
            // xhr.setRequestHeader('userPhone', 13505711755);

            xhr.send();
        });
  }else{
    return fetchOld(server + options.url,{
      method: 'post',
      headers: {
        'userId':userId
      },
      body:options.params
    })
  }

}

//jason格式转化为?key=value&格式的字符串
var jasonToString = function(params){
  let str = '';
  if(params){
    str = '?'
  }else{
    return '';
  }
  for(var param in params){
    str = str + param + '=' + params[param] + '&';
  }
  return str;
}

callApi = (options) =>{
  return fetchnew(options).then(res=>{
        return JSON.parse(res);
      
    })
}


const ThreeBattleMobileAjax = {
  callApi
}

ecodeSDK.exp(ThreeBattleMobileAjax);

上一篇:使用mobx 创建前端store并使用


下一篇:mobx模板用法