redux 登录
/** * 系统登录 * * @route SystemLogin * @date 2017-09-18 * @author wuxiaoyan<408991702@qq.com> */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { Link,hashHistory } from 'react-router'; import { Form, Icon, Input, Button, Checkbox } from 'antd'; import * as systemAction from '../../store/actions/system'; import common from '../../configs/common'; import {toastShort} from '../../utils/Toast'; function mapStateToProps(state) { const { system } = state; return { system }; } class systemLogin extends React.Component { static get propTypes() { return { system: PropTypes.object, }; } // 初始化页面 constructor(props, context) { super(props); this.pageFlag='SystemLogin'; this.state = { element:{//表单元素 username:{ value:'22', require:true, errorTip:'请输入账号', }, password:{ value:'33', require:true, errorTip:'请输入密码', } } }; } componentWillReceiveProps(nextProps) { const { system } = this.props; // 提交成功 if (system.formSubmit.pageFlag===this.pageFlag && system.formSubmit.receiveSystemFormSubmitLoading && !nextProps.system.formSubmit.receiveSystemFormSubmitLoading && nextProps.system.formSubmit.receiveSystemFormSubmitSucess) { toastShort('登录成功'); sessionStorage.USER_API_TOKEN=nextProps.system.formSubmit.receiveData.result.token; hashHistory.push('/'); } } //提交 _submit(e){ e.preventDefault(); const { dispatch,system } = this.props; //验证重复提交 if(system.formSubmit.pageFlag===this.pageFlag && system.formSubmit.receiveSystemFormSubmitLoading) { return false; } this.props.form.validateFields((err, values) => { if (!err) { let subParams={}; //拼接url参数 for(var key in values){ if(values[key] !=='') { subParams[key]=values[key] ; } } dispatch(systemAction.requestSystemFormSubmit(this.pageFlag,common.api.URI_SYSTEM_LOGIN,subParams)); } }); } render() { const {system}=this.props; const { getFieldDecorator } = this.props.form; return ( <div style={{ ...common.theme.commonFlexStyle, flex:1, height:'100%', alignItems:'center', justifyContent:'center', background: 'url(images/system/login_bg.png) center center no-repeat' }} > <Form onSubmit={this._submit.bind(this)} style={{ width: 350, background: '#fff', padding: '30px 50px', borderRadius: 10 }} className="animated bounceInLeft" > <Form.Item> {getFieldDecorator('username', { rules: [{ required: true, message: '请输入您的账号!' }], })( <Input prefix={<Icon type="user" style={{ fontSize: 18 }} />} placeholder="账号" /> )} </Form.Item> <Form.Item> {getFieldDecorator('password', { rules: [{ required: true, message: '请输入您的密码!' }], })( <Input prefix={<Icon type="lock" style={{ fontSize: 18 }} />} type="password" placeholder="密码" /> )} </Form.Item> {/*<Form.Item> {getFieldDecorator('remember', { valuePropName: 'checked', initialValue: true, })( <Checkbox>记住用户名和密码</Checkbox> )} </Form.Item>*/} <Form.Item style={{ textAlign:'center' }} > <Button type="primary" htmlType="submit" style={{ width:'80%' }} > 登录 </Button> </Form.Item> </Form> </div> ); } } export default connect(mapStateToProps)(Form.create()(systemLogin));
actions
/** * 系统化表单、列表 - action组件 * * @date 2017-07-31 * @author wuxiaoyan<408991702@qq.com> */ /** * 自定义提交表单 * @param {pageFlag} 页面标志 * @param {submitUrl} 提交URL * @param {params} 参数列表 */ export function requestSystemFormSubmit(pageFlag,submitUrl,params) { return { type: 'REQUEST_SYSTEM_FORM_SUBMIT', pageFlag, submitUrl, params, }; } export function fetchSystemFormSubmit(pageFlag) { return { type: 'FETCH_SYSTEM_FORM_SUBMIT', pageFlag, }; } export function receiveSystemFormSubmit(pageFlag,isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_FORM_SUBMIT', pageFlag, isSuccess, receiveData }; } /** * // 获取知识库详情页面 * @param {pageFlag} 页面标志 * @param {queryUrl} 查询URL * @param {params} 参数列表 */ export function requestSystemKnowledgeBaseDetail(params) { return { type: 'REQUEST_SYSTEM_KNOWLEDGEBASE_DETAIL', params }; } export function fetchSystemKnowledgeBaseDetail() { return { type: 'FETCH_SYSTEM_KNOWLEDGEBASE_DETAIL', }; } export function receiveSystemKnowledgeBaseDetail(isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_KNOWLEDGEBASE_DETAIL', isSuccess, receiveData }; } /** * 获取知识库列表页面 * @param {PagerAction} pagerAction - 列表操作对象 */ export function requestSystemKnowledgeBaseList(pagerAction) { return { type: 'REQUEST_SYSTEM_KNOWLEDGEBASE_LIST', pagerAction }; } export function fetchSystemKnowledgeBaseList(pagerAction) { return { type: 'FETCH_SYSTEM_KNOWLEDGEBASE_LIST', pagerAction, }; } export function receiveSystemKnowledgeBaseList(data, total) { return { type: 'RECEIVE_SYSTEM_KNOWLEDGEBASE_LIST', data, total }; } /** * // 获取没有分页的列表页面 * @param {queryUrl} 查询URL * @param {params} 参数列表 */ export function requestSystemSinglePage(queryUrl,params) { return { type: 'REQUEST_SYSTEM_SINGLE_PAGE', queryUrl, params }; } export function fetchSystemSinglePage() { return { type: 'FETCH_SYSTEM_SINGLE_PAGE', }; } export function receiveSystemSinglePage(isSuccess,data) { return { type: 'RECEIVE_SYSTEM_SINGLE_PAGE', isSuccess, data }; } /** * 获消息单列表 * @param {PagerAction} pagerAction - 列表操作对象 */ export function requestSystemMessageList(pagerAction) { return { type: 'REQUEST_SYSTEM_MESSAGE_LIST', pagerAction }; } export function fetchSystemMessageList(pagerAction) { return { type: 'FETCH_SYSTEM_MESSAGE_LIST', pagerAction, }; } export function receiveSystemMessageList(data, total) { return { type: 'RECEIVE_SYSTEM_MESSAGE_LIST', data, total }; } /** * // 获取消息详情页面 * @param {params} 参数列表 */ export function requestSystemMessageDetail(params) { return { type: 'REQUEST_SYSTEM_MESSAGE_DETAIL', params }; } export function fetchSystemMessageDetail() { return { type: 'FETCH_SYSTEM_MESSAGE_DETAIL', }; } export function receiveSystemMessageDetail(isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_MESSAGE_DETAIL', isSuccess, receiveData }; } /** * 获取探索业务列表页面 * @param {PagerAction} pagerAction - 列表操作对象 */ export function requestSystemExplorationList(pagerAction) { return { type: 'REQUEST_SYSTEM_EXPLORATION_LIST', pagerAction }; } export function fetchSystemExplorationList(pagerAction) { return { type: 'FETCH_SYSTEM_EXPLORATION_LIST', pagerAction, }; } export function receiveSystemExplorationList(data, total) { return { type: 'RECEIVE_SYSTEM_EXPLORATION_LIST', data, total }; } /** * // 获取探索业务轮播图片 * @param {params} 参数列表 */ export function requestSystemExplorationPic(params) { return { type: 'REQUEST_SYSTEM_EXPLORATION_PIC', params }; } export function fetchSystemExplorationPic() { return { type: 'FETCH_SYSTEM_EXPLORATION_PIC', }; } export function receiveSystemExplorationPic(isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_EXPLORATION_PIC', isSuccess, receiveData }; } /** * // 获取维修师首页数据 * @param {params} 参数列表 */ export function requestSystemHomeDate(params) { return { type: 'REQUEST_SYSTEM_HOME_DATE', params }; } export function fetchSystemHomeDate() { return { type: 'FETCH_SYSTEM_HOME_DATE', }; } export function receiveSystemHomeDate(isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_HOME_DATE', isSuccess, receiveData }; } /** * // 获取客户端首页数据 * @param {params} 参数列表 */ export function requestSystemCustomerDate(params) { return { type: 'REQUEST_SYSTEM_CUSTOMER_DATE', params }; } export function fetchSystemCustomerDate() { return { type: 'FETCH_SYSTEM_CUSTOMER_DATE', }; } export function receiveSystemCustomerDate(isSuccess,receiveData) { return { type: 'RECEIVE_SYSTEM_CUSTOMER_DATE', isSuccess, receiveData }; }
reducers
/** * 系统配置化表单提交、列表获取 - reducer组件 * * @date 2017-07-17 * @author wuxiaoyan<408991702@qq.com> * */ import { Pager } from '../pager'; const initialState = { messageList:new Pager(), knowledgeBaseList:new Pager(), explorationList:new Pager(), formSubmit: {//表单提交 pageFlag:'',//页面标识 receiveSystemFormSubmitLoading:false,//提交后Loading标志 receiveSystemFormSubmitSucess:false,//提交是否成功标志 receiveData:{},//接收参数 }, //知识库详情页面 KnowledgeBaseDetail_Loading:false,//Loading标志 KnowledgeBaseDetail_Sucess:false,//是否成功标志 KnowledgeBaseDetail_Data:{},//接收参数 //消息详情页面 MessageDetail_Loading:false, MessageDetail_Sucess:false, MessageDetail_Data:{}, //探索业务轮播图片 ExplorationPic_Loading:false, ExplorationPic_Sucess:false, ExplorationPic_Data:{}, //获取维修师首页数据 HomeData_Loading:false, HomeData_Sucess:false, HomeData_Data:{}, //获取客户端首页数据 CustomerHomeData_Loading:false, CustomerHomeData_Sucess:false, CustomerHomeData_Data:{}, systemSinglePage:{//没有分页的列表 systemSinglePageLoading:false,//Loading标志 systemSinglePageSucess:false,//是否成功标志 list:null,//接收参数 } }; export default function system(state = initialState, action) { switch (action.type) { //提交表单 case 'FETCH_SYSTEM_FORM_SUBMIT': return Object.assign( {}, state, { formSubmit:{ pageFlag:action.pageFlag, receiveSystemFormSubmitLoading:true, receiveSystemFormSubmitSucess:false, receiveData:{} } } ); case 'RECEIVE_SYSTEM_FORM_SUBMIT': return Object.assign( {}, state, { formSubmit:{ pageFlag:action.pageFlag, receiveSystemFormSubmitLoading:false, receiveSystemFormSubmitSucess:action.isSuccess, receiveData:action.receiveData } } ); //获取知识库详情页面 case 'FETCH_SYSTEM_KNOWLEDGEBASE_DETAIL': return Object.assign( {}, state, { KnowledgeBaseDetail_Loading:true, KnowledgeBaseDetail_Sucess:false, KnowledgeBaseDetail_Data:{} } ); case 'RECEIVE_SYSTEM_KNOWLEDGEBASE_DETAIL': return Object.assign( {}, state, { KnowledgeBaseDetail_Loading:false, KnowledgeBaseDetail_Sucess:action.isSuccess, KnowledgeBaseDetail_Data:action.receiveData } ); //获取知识库列表页面 case 'FETCH_SYSTEM_KNOWLEDGEBASE_LIST': return Object.assign({}, state, { knowledgeBaseList: state.knowledgeBaseList.fetch(action.pagerAction) }); case 'RECEIVE_SYSTEM_KNOWLEDGEBASE_LIST': return Object.assign({}, state, { knowledgeBaseList: state.knowledgeBaseList.receive(action.data, action.total) }); //没有分页的列表 case 'FETCH_SYSTEM_SINGLE_PAGE': return Object.assign( {}, state, { systemSinglePage:{ systemSinglePageLoading:true, systemSinglePageSucess:false, list:{} } } ); case 'RECEIVE_SYSTEM_SINGLE_PAGE': return Object.assign( {}, state, { systemSinglePage:{ systemSinglePageLoading:false, systemSinglePageSucess:action.isSuccess, list:action.data } } ); //获取消息列表 case 'FETCH_SYSTEM_MESSAGE_LIST': return Object.assign({}, state, { messageList: state.messageList.fetch(action.pagerAction) }); case 'RECEIVE_SYSTEM_MESSAGE_LIST': return Object.assign({}, state, { messageList: state.messageList.receive(action.data, action.total) }); //获取消息详情页面 case 'FETCH_SYSTEM_MESSAGE_DETAIL': return Object.assign( {}, state, { MessageDetail_Loading:true, MessageDetail_Sucess:false, MessageDetail_Data:{} } ); case 'RECEIVE_SYSTEM_MESSAGE_DETAIL': return Object.assign( {}, state, { MessageDetail_Loading:false, MessageDetail_Sucess:action.isSuccess, MessageDetail_Data:action.receiveData } ); //探索业务轮播图片 case 'FETCH_SYSTEM_EXPLORATION_PIC': return Object.assign( {}, state, { ExplorationPic_Loading:true, ExplorationPic_Sucess:false, ExplorationPic_Data:{} } ); case 'RECEIVE_SYSTEM_EXPLORATION_PIC': return Object.assign( {}, state, { ExplorationPic_Loading:false, ExplorationPic_Sucess:action.isSuccess, ExplorationPic_Data:action.receiveData } ); //获取探索业务列表 case 'FETCH_SYSTEM_EXPLORATION_LIST': return Object.assign({}, state, { explorationList: state.explorationList.fetch(action.pagerAction) }); case 'RECEIVE_SYSTEM_EXPLORATION_LIST': return Object.assign({}, state, { explorationList: state.explorationList.receive(action.data, action.total) }); //探索维修师首页数据 case 'FETCH_SYSTEM_HOME_DATE': return Object.assign( {}, state, { HomeData_Loading:true, HomeData_Sucess:false, HomeData_Data:{} } ); case 'RECEIVE_SYSTEM_HOME_DATE': return Object.assign( {}, state, { HomeData_Loading:false, HomeData_Sucess:action.isSuccess, HomeData_Data:action.receiveData } ); //探索客户端首页数据 case 'FETCH_SYSTEM_CUSTOMER_DATE': return Object.assign( {}, state, { CustomerHomeData_Loading:true, CustomerHomeData_Sucess:false, CustomerHomeData_Data:{} } ); case 'RECEIVE_SYSTEM_CUSTOMER_DATE': return Object.assign( {}, state, { CustomerHomeData_Loading:false, CustomerHomeData_Sucess:action.isSuccess, CustomerHomeData_Data:action.receiveData } ); default: return state; } }
sagas
/** * 系统化表单、列表 - saga组件 * * @date 2017-07-17 * @author wuxiaoyan<408991702@qq.com> */ import { put, take, call, fork } from 'redux-saga/effects'; import * as ApiClient from '../../utils/ApiClient'; import Storage from '../../utils/Storage'; import common from '../../configs/common'; import { fetchSystemFormSubmit, receiveSystemFormSubmit, fetchSystemKnowledgeBaseDetail, receiveSystemKnowledgeBaseDetail, fetchSystemKnowledgeBaseList, receiveSystemKnowledgeBaseList, fetchSystemSinglePage, receiveSystemSinglePag, fetchSystemMessageList, receiveSystemMessageList, fetchSystemMessageDetail, receiveSystemMessageDetail, fetchSystemExplorationList, receiveSystemExplorationList, fetchSystemExplorationPic, receiveSystemExplorationPic, fetchSystemHomeDate, receiveSystemHomeDate, fetchSystemCustomerDate, receiveSystemCustomerDate } from '../actions/system'; // 自定义提交表单 export function* requestSystemFormSubmit(pageFlag,submitUrl,params) { try { yield put(fetchSystemFormSubmit(pageFlag)); let res; if(submitUrl.indexOf('login')>=0) { res = yield call(ApiClient.postForm, submitUrl, params); }else{ res = yield call(ApiClient.postForm, submitUrl, params); } //const res = yield call(ApiClient.postForm, submitUrl, params); if (common.api.validResponse(res)) { yield put(receiveSystemFormSubmit(pageFlag,true,res)); } else { yield put(receiveSystemFormSubmit(pageFlag,false,res)); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemFormSubmit(pageFlag,false,{})); } } export function* watchRequestSystemFormSubmit() { while (true) { const { pageFlag,submitUrl,params } = yield take('REQUEST_SYSTEM_FORM_SUBMIT'); yield fork(requestSystemFormSubmit, pageFlag,submitUrl,params); } } // 公共知识库详情页面 export function* requestSystemKnowledgeBaseDetail(params) { try { yield put(fetchSystemKnowledgeBaseDetail()); const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_KNOWLEDGEBASEDETAIL, params); if (common.api.validResponse(res)) { yield put(receiveSystemKnowledgeBaseDetail(true,res.result)); } else { yield put(receiveSystemKnowledgeBaseDetail(false,{})); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemKnowledgeBaseDetail(false,{})); } } export function* watchRequestSystemKnowledgeBaseDetail() { while (true) { const { params } = yield take('REQUEST_SYSTEM_KNOWLEDGEBASE_DETAIL'); yield fork(requestSystemKnowledgeBaseDetail,params); } } // 获取知识库列表页面 export function* requestSystemKnowledgeBaseList(pagerAction) { try { yield put(fetchSystemKnowledgeBaseList(pagerAction)); const { pageNum, pageSize } = pagerAction.params; let params={ page: pageNum + '', size: pageSize + '',...pagerAction.params}; delete params.pageNum; delete params.pageSize; const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_KNOWLEDGEBASE, params); if (common.api.validResponse(res)) { if (res.result && res.result.content ) { yield put(receiveSystemKnowledgeBaseList(res.result.content, res.result.totalElements)); } else { yield put(receiveSystemKnowledgeBaseList([], 0)); } } else { yield put(receiveSystemKnowledgeBaseList([], -1)); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemKnowledgeBaseList([], -1)); } } export function* watchRequestSystemKnowledgeBaseList() { while (true) { const { pagerAction } = yield take('REQUEST_SYSTEM_KNOWLEDGEBASE_LIST'); yield fork(requestSystemKnowledgeBaseList,pagerAction); } } // 获取公共没有分页的列表页面 export function* requestSystemSinglePage(queryUrl,params) { try { yield put(fetchSystemSinglePage()); if (typeof(params)=='undefined'){ params={ page:-1 } }else{ params={...params,page:-1} } const res = yield call(ApiClient.postForm, queryUrl, params); if (common.api.validResponse(res)) { yield put(receiveSystemSinglePage(true,res.result)); } else { yield put(receiveSystemSinglePage(false,[])); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemSinglePage(false,[])); } } export function* watchRequestSystemSinglePage() { while (true) { const { queryUrl,params } = yield take('REQUEST_SYSTEM_SINGLE_PAGE'); yield fork(requestSystemSinglePage, queryUrl,params); } } // 获取消息列表 export function* requestSystemMessageList(pagerAction) { try { yield put(fetchSystemMessageList(pagerAction)); const { pageNum, pageSize } = pagerAction.params; let params={ page: pageNum + '', size: pageSize + '',...pagerAction.params}; delete params.pageNum; delete params.pageSize; const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_MESSAGE, params); if (common.api.validResponse(res)) { if (res.result && res.result.content ) { yield put(receiveSystemMessageList(res.result.content, res.result.totalElements)); } else { yield put(receiveSystemMessageList([], 0)); } } else { yield put(receiveSystemMessageList([], -1)); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemMessageList([], -1)); } } export function* watchRequestSystemMessageList() { while (true) { const { pagerAction } = yield take('REQUEST_SYSTEM_MESSAGE_LIST'); yield fork(requestSystemMessageList, pagerAction); } } // 公共消息详情页面 export function* requestSystemMessageDetail(params) { try { yield put(fetchSystemMessageDetail()); const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_MESSAGE_DETAIL, params); if (common.api.validResponse(res)) { yield put(receiveSystemMessageDetail(true,res.result)); } else { yield put(receiveSystemMessageDetail(false,{})); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemMessageDetail(false,{})); } } export function* watchRequestSystemMessageDetail() { while (true) { const { params } = yield take('REQUEST_SYSTEM_MESSAGE_DETAIL'); yield fork(requestSystemMessageDetail,params); } } // 获取探索业务列表页面 export function* requestSystemExplorationList(pagerAction) { try { yield put(fetchSystemExplorationList(pagerAction)); const { pageNum, pageSize } = pagerAction.params; let params={ page: pageNum + '', size: pageSize + '',...pagerAction.params}; delete params.pageNum; delete params.pageSize; const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_EXPLORATIONBUSINESS, params); if (common.api.validResponse(res)) { if (res.result && res.result.content ) { yield put(receiveSystemExplorationList(res.result.content, res.result.totalElements)); } else { yield put(receiveSystemExplorationList([], 0)); } } else { yield put(receiveSystemExplorationList([], -1)); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemExplorationList([], -1)); } } export function* watchRequestSystemExplorationList() { while (true) { const { pagerAction } = yield take('REQUEST_SYSTEM_EXPLORATION_LIST'); yield fork(requestSystemExplorationList,pagerAction); } } // 探索业务轮播图片 export function* requestSystemExplorationPic(params) { try { yield put(fetchSystemExplorationPic()); const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_EXPLORATION_PIC, params); if (common.api.validResponse(res)) { yield put(receiveSystemExplorationPic(true,res.result)); } else { yield put(receiveSystemExplorationPic(false,{})); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemExplorationPic(false,{})); } } export function* watchRequestSystemExplorationPic() { while (true) { const { params } = yield take('REQUEST_SYSTEM_EXPLORATION_PIC'); yield fork(requestSystemExplorationPic, params); } } // 获取维修师首页数据 export function* requestSystemHomeDate(params) { try { yield put(fetchSystemHomeDate()); const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_MAINTAIN_HOMEDATA, params); if (common.api.validResponse(res)) { yield put(receiveSystemHomeDate(true,res.result)); } else { yield put(receiveSystemHomeDate(false,{})); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemHomeDate(false,{})); } } export function* watchRequestSystemHomeDate() { while (true) { const { params } = yield take('REQUEST_SYSTEM_HOME_DATE'); yield fork(requestSystemHomeDate, params); } } // 获取维修师首页数据 export function* requestSystemCustomerDate(params) { try { yield put(fetchSystemCustomerDate()); const res = yield call(ApiClient.postForm, common.api.URI_SYSTEM_MAINTAIN_HOMEDATA, params); if (common.api.validResponse(res)) { yield put(receiveSystemCustomerDate(true,res.result)); } else { yield put(receiveSystemCustomerDate(false,{})); } } catch (error) { common.api.getErrorTip(error); yield put(receiveSystemCustomerDate(false,{})); } } export function* watchRequestSystemCustomerDate() { while (true) { const { params } = yield take('REQUEST_SYSTEM_CUSTOMER_DATE'); yield fork(requestSystemCustomerDate, params); } }
ajax
import fetch from 'isomorphic-fetch' import { API_PREFIX, API_SUFFIX } from '../constants' // todo : 连接store // const code = global.$GLOBALCONFIG.STAFF.code function buildParams(obj) { if (!obj) { return '' } const params = [] for (const key of Object.keys(obj)) { const value = obj[key] === undefined ? '' : obj[key] params.push(`${key}=${encodeURIComponent(value)}`) } const arg = params.join('&') return arg } // 下面是注释用formdata的方式传输数据 /*export function fetchJSON(url, params) { params = { ...params, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', ...params.headers, }, } url = `${API_PREFIX}${url}${API_SUFFIX}` return fetch(url, params) }*/ export function fetchJSON(url, params, target) { let data = { 'method': 'POST', 'Content-Type': 'application/json', 'body': JSON.stringify(params) } if(target){ url = `${target}${url}${API_SUFFIX}` } else { url = `${API_PREFIX}${url}${API_SUFFIX}` } return fetch(url, data) } // eslint-disable-next-line arrow-parens export const fetchJSONByPost = (url, target) => query => { // 下面是注释用formdata的方式传输数据 /*const params = { method: 'POST', body: buildParams(query), } return fetchJSON(url, params)*/ return fetchJSON(url, query, target) } export const fetchJSONStringByPost = url => query => { const params = { method: 'POST', body: query, headers: { 'Content-Type': 'application/json;charset=UTF-8', }, } return fetchJSON(url, params) }
本地存储操作工具 Storage.js
/** * 本地存储操作工具 * * @date 2017-05-09 * @author shuwenjie<4483378@qq.com> */ class DeviceStorage { static saveToken(token) { return null; } static getToken() { return sessionStorage.getItem('USER_API_TOKEN'); } static getToken(key) { return sessionStorage.getItem(key); } } export default DeviceStorage;
广告图轮播组件
/** * 广告图轮播组件 * * @date 2017-07-08 * @author wuxiaoyan<408991702@qq.com> */ /** * 引用格式 * <BannerScroll height={200} navigation={navigation} dataList={}/> */ /** * 配置格式 * dataList:[ { url:'SystemLogin', //跳转链接 选填 默认30 path:require('../../images/index/u84.jpg') } ] */ import React,{PropTypes} from 'react'; import { Image, TouchableOpacity } from 'react-native'; import ViewPager from 'react-native-viewpager'; import common from '../../configs/common'; class BannerScroll extends React.Component { // injection reduer object and other params static get propTypes() { return { dataList: PropTypes.array, height: PropTypes.number, }; } constructor(props) { super(props); this.renderPage = this.renderPage.bind(this); this.bannerImgClick = this.bannerImgClick.bind(this); let dataSource=new ViewPager.DataSource({ pageHasChanged:(p1,p2)=> p1!==p2, }); // Initialize the view state this.state = { dataSource:dataSource.cloneWithPages(this.props.dataList) }; } //渲染单张轮播图 renderPage(data,pageID){ let url=data?data.url:''; if(data.url){ return( <TouchableOpacity style={{ flex: 1, width:common.size.width, height:this.props.height, }} onPress={this.bannerImgClick.bind(this, url)} > <Image source={data.path} style={{ width:common.size.width, flex:1, height:this.props.height, resizeMode:'stretch' }} /> </TouchableOpacity> ); }else{ return( <Image source={data.path} style={{ width:common.size.width, flex:1, height:this.props.height, resizeMode:'stretch' }} /> ); } } //图片点击事件 bannerImgClick(url){ const {navigation} = this.props; navigation.navigate(url); } render() { return ( <ViewPager style={{height:this.props.height}} dataSource={this.state.dataSource} renderPage={this.renderPage} isLoop={true} autoPlay={true}/> ); } } // export redux component export default BannerScroll;
日历组件
/** * 日历组件 * * @date 2017-08-10 * @author wuxiaoyan<408991702@qq.com> */ import React from 'react' import {render} from 'react-dom' import CalendarHeader from './CalendarHeader' import CalendarMain from './CalendarMain' const displayDaysPerMonth = (year)=> { //定义每个月的天数,如果是闰年第二月改为29天 let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { daysInMonth[1] = 29 } //以下为了获取一年中每一个月在日历选择器上显示的数据, //从上个月开始,接着是当月,最后是下个月开头的几天 //定义一个数组,保存上一个月的天数 let daysInPreviousMonth = [].concat(daysInMonth) daysInPreviousMonth.unshift(daysInPreviousMonth.pop()) //获取每一个月显示数据中需要补足上个月的天数 let addDaysFromPreMonth = new Array(12) .fill(null) .map((item, index)=> { let day = new Date(year, index, 1).getDay() if (day === 0) { return 6 } else { return day } }) //已数组形式返回一年中每个月的显示数据,每个数据为6行*7天 return new Array(12) .fill([]) .map((month, monthIndex)=> { let addDays = addDaysFromPreMonth[monthIndex], daysCount = daysInMonth[monthIndex], daysCountPrevious = daysInPreviousMonth[monthIndex], monthData = [] //补足上一个月 for (; addDays > 0; addDays--) { monthData.unshift(daysCountPrevious--) } //添入当前月 for (let i = 0; i < daysCount;) { monthData.push(++i) } //补足下一个月 for (let i = 42 - monthData.length, j = 0; j < i;) { monthData.push(++j) } return monthData }) } class Calendar extends React.Component { constructor() { //继承React.Component super() let now = new Date() this.state = { year: now.getFullYear(), month: now.getMonth(), day: now.getDate(), //picked: false } } componentDidMount() { this.datePick(new Date().getDate()); } //切换到下一个月 nextMonth() { if (this.state.month === 11) { this.setState({ year: ++this.state.year, month: 0 }) } else { this.setState({ month: ++this.state.month }) } } //切换到上一个月 prevMonth() { if (this.state.month === 0) { this.setState({ year: --this.state.year, month: 11 }) } else { this.setState({ month: --this.state.month }) } } //选择日期 datePick(day) { const {onValueChange}=this.props; this.setState({day},()=>{ if(onValueChange) onValueChange(this.state.year,this.state.month,this.state.day); }); } //标记日期已经选择 picked() { this.state.picked = true } render() { let props = { viewData: displayDaysPerMonth(this.state.year), datePicked: `${this.state.year} 年 ${this.state.month + 1} 月 ${this.state.day} 日` } const {style}=this.props; return ( <div style={{ ...style, color:'#fff' }} ref="main" > <CalendarHeader prevMonth={::this.prevMonth} nextMonth={::this.nextMonth} year={this.state.year} month={this.state.month} day={this.state.day}/> <CalendarMain {...props} prevMonth={::this.prevMonth} nextMonth={::this.nextMonth} datePick={::this.datePick} year={this.state.year} month={this.state.month} day={this.state.day}/> </div> ) } } //将calender实例添加到window上以便获取日期选择数据 export default Calendar;
日历头部
CalendarHeader.js
import React from 'react' export default class CalendarHeader extends React.Component { render() { return ( <div style={{ display:'flex', flexDirection:'row', alignItems:'center', height:'.8rem' }} > <div style={{ display:'flex', width:'1rem', justifyContent:'center', fontSize:'.4rem' }} onClick={this.props.prevMonth} > < </div> <div style={{ display:'flex', flex:1, justifyContent:'center', fontSize:'.3rem' }} > {this.props.year}年{this.props.month + 1}月 </div> <div style={{ display:'flex', width:'1rem', justifyContent:'center', fontSize:'.4rem' }} onClick={this.props.nextMonth} > > </div> </div> ) } }
CalendarMain.js
import React from 'react' export default class CalendarMain extends React.Component { //处理日期选择事件,如果是当月,触发日期选择;如果不是当月,切换月份 handleDatePick(index, styleName) { switch (styleName) { case 'thisMonth': let month = this.props.viewData[this.props.month] this.props.datePick(month[index]) break case 'prevMonth': this.props.prevMonth() break case 'nextMonth': this.props.nextMonth() break } } //处理选择时选中的样式效果 //利用闭包保存上一次选择的元素, //在月份切换和重新选择日期时重置上一次选择的元素的样式 changeColor() { let previousEl = null return function (event) { let name = event.target.nodeName.toLocaleLowerCase() if (previousEl && (name === 'i' || name === 'td')) { previousEl.style = '' } if (event.target.className === 'thisMonth') { event.target.style = 'background:#F8F8F8;color:#000' previousEl = event.target } } } //绑定颜色改变事件 componentDidMount() { // let changeColor = this.changeColor() // document.getElementById('calendarContainer') // .addEventListener('click', changeColor, false); } render() { //确定当前月数据中每一天所属的月份,以此赋予不同className let month = this.props.viewData[this.props.month], rowsInMonth = [], i = 0, styleOfDays = (()=> { let i = month.indexOf(1), j = month.indexOf(1, i + 1), arr = new Array(42) arr.fill('prevMonth', 0, i) arr.fill('thisMonth', i, j) arr.fill('nextMonth', j) return arr })() //把每一个月的显示数据以7天为一组等分 month.forEach((day, index)=> { if (index % 7 === 0) { rowsInMonth.push(month.slice(index, index + 7)) } }) return ( <table style={{ width:'100%' }} > <thead> <tr style={{ lineHeight:'.6rem' }} > <th style={{ fontSize:'.25rem' }} > 日 </th> <th style={{ fontSize:'.25rem' }} >一</th> <th style={{ fontSize:'.25rem' }} >二</th> <th style={{ fontSize:'.25rem' }} >三</th> <th style={{ fontSize:'.25rem' }} >四</th> <th style={{ fontSize:'.25rem' }} >五</th> <th style={{ fontSize:'.25rem' }} >六</th> </tr> </thead> <tbody> { rowsInMonth.map((row, rowIndex)=> { return ( <tr key={rowIndex}> { row.map((day)=> { let tdStyle={}; if(this.props.day==day && styleOfDays[i]=='thisMonth'){ tdStyle={ backgroundColor:'#11ACE9' }; } if(styleOfDays[i]!='thisMonth'){ tdStyle={ backgroundColor:'rgba(40,40,40,0.1)', color:'rgba(180,180,180,1)' }; } return ( <td style={{ backgroundColor:'rgba(255,255,255,0.1)', textAlign:'center', lineHeight:'.8rem', fontSize:'.25rem', ...tdStyle }} onClick={ this.handleDatePick.bind (this, i, styleOfDays[i])} key={i++}> {day} </td> ) }) } </tr> ) }) } </tbody> </table> ) } }