Author:Mr.柳上原
- 付出不亚于任何的努力
- 愿我们所有的努力,都不会被生活辜负
- 不忘初心,方得始终
代码语言:javascript复制在RN中 项目实际开发时Redux全局参数的具体使用方法 Redux的好处: 可以把一些全局都需要使用的参数保存起来,并且在一个组件里更新这个参数后,全局里任何使用这个参数的地方都能实时更新 适用于购物车,图标右上角数字,form表单数据字典配置,权限配置,实时消息数量等等
client页面
// 此处使用了redux-actions
import { handleActions } from 'redux-actions'
import * as actionTypes from '../constants' // 定义 actionTypes
const initState = {
a: {},
b: 0,
c: [],
... // 存储数值
}
const map = {}
map[actionTypes.SEARCH_GET_PURCH_LIST] = (state, action) => {
let value = action.payload.values
return Object.assign({}, state, {b: value})
}
map[actionTypes.SEARCH_GET_REALESTATE_LIST] = (state, action) => {
let value = state.c.concat([{
name: action.payload.name,
id: action.payload.number === '不限' ? null : action.payload.shop.id,
}])
return Object.assign({}, state, {c: value})
}
代码语言:javascript复制constants页面
// actionTypes
export const SEARCH_GET_PURCH_LIST = "SEARCH_GET_PURCH_LIST";
export const SEARCH_GET_REALESTATE_LIST = "SEARCH_GET_REALESTATE_LIST";
...
...
代码语言:javascript复制action页面
// 此处使用了redux-actions
import {createAction} from 'redux-actions';
import * as actionTypes from '../constants';
export const getPurchListForm = createAction(actionTypes.SEARCH_GET_PURCH_LIST)
export const getRealEstateForm = createAction(actionTypes.SEARCH_GET_REALESTATE_LIST)
代码语言:javascript复制具体组件里面调用Redux保存的参数
// 详情页面
import React, {Component} from 'react'
import {connect} from 'react-redux'
import { store } from '../index';
class RealEstate extends Component {
.....
this.props.a // 取值
this.props.b // 取值
this.props.c // 取值
// 修改Redux的值
this.props.dispatch(getPurchListForm(this.props.b - 1)) // 方法一
/**export const store = configure({})
global.store = store*/ // 全局 index 页面定义 store 并导入到当前页
store.dispatch(getPurchListForm(this.props.b - 1)) // 方法二
}
const mapStateToProps = (state, props) => {
return {
a: state.client.a
b: state.client.b
c: state.client.c
}
}
const mapDispatchToProps = (dispatch) => {
return {
deleteRealEstate: (...args) => dispatch(deleteRealEstate(...args)),
dispatch
}
}
export default connect(mapStateToProps, mapDispatchToProps)(RealEstate)