react获取state的值并更新使用

react获取state的值并且修改分为两种情况:


在视图层处理:

//在 state 中饭设置初始值
state={
      name:'',
      age:''
 }

//通过 控制一个事件触发然后setState 去设置
setName=()=>{
    this.setState({
       name
    })
}

在model层处理:

view层

  //前端通过dispatch 去调用changeTab 接口

  onTabsChange = (key) => {  
    this.props.dispatch({
      type: `${this.module}/changeTab`,  
      payload: key
    });
  }

model层:

const moduleName = 'mayouchen';
let defaultState = {
  activeTabKey: "1"
};
export default {
  namespace: moduleName,
  state: {
    moduleName: moduleName,
    defaultState,
    ...defaultState
},
effects: {
 * changeTab({ payload, }, { call, put, select }) {  

       // 更新  activeTabKey  

       yield put({
         type:'updateActiveTabKey',
         payload
       }); 

      // 更新完  activeTabKey  就可以使用  activeTabKey 更新后的值

       yield put({type: 'getDataByTab'});
 },
  * getDataByTab({payload }, { call, put, select }) { 

        let { activeTabKey } = yield select(state => state[moduleName]);

        //切换TAB调用不同接口
        if(activeTabKey == "1") {  //商户信息
          yield put({type:'businessInformation', payload: {}});
        } else if (activeTabKey == "2" ) {  //审批信息
          yield put({type:'approvalInformation', payload: {}})
        }else if (activeTabKey == "3" ) {
        }
    }, 
   * businessInformation ({payload, }, { call, put, select }) {
     const result = yield call(read, payload);
     if (result ) {
       let { data } = result ;
       yield put({ type: 'getBusinessInformationData', payload: {...data }});
     }
     else {
       message.error(`获取信息失败:${entityRes.globalError}`);
     }
  }
}
 reducers: {
     updateActiveTabKey(state, action) {
      return {
        ...state,
        activeTabKey: action.payload
      };
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24147051/article/details/80801802
今日推荐