Taro -- 使用 Redux 来进行全局变量的管理

前言

Redux是JavaScript 状态容器,提供可预测化的状态管理。一般来说,规模比较大的小程序,页面状态,数据缓存,需要管理的东西太多,这时候引入Redux可以方便的管理这些状态,同一数据,一次请求,应用全局共享。

而Taro也非常友好地为开发者提供了移植的Redux。

为了更方便地使用Redux,Taro提供了与react-redux API 几乎一致的包 @tarojs/redux 来让开发人员获得更加良好的开发体验。

使用 Redux 来进行全局变量的管理

1、在pages 同级目录新建4个文件夹。
store、actions、reducers、constants

store: 创建全局单一的store。

actions:用于描述发生什么事件。

reducers:用于action如何改变state树。

constants:用于定义所需的action type常量。

//store/index.js文件

import { createStore, applyMiddleware, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers'

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
      // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
    }) : compose

const middlewares = [
  thunkMiddleware
]

if (process.env.NODE_ENV === 'development') {
  middlewares.push(require('redux-logger').createLogger())
}

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares),
  // other store enhancers if any
)

export default function configStore () {
  const store = createStore(rootReducer, enhancer)
  return store
}

首先在app.js中引入一开始定义好的store,使用@tarojs/redux中提供的Provider组件将前面写好的store接入应用中,这样一来,被Provider包裹的页面都能共享到应用的store

//app.js
import Taro, { Component } from '@tarojs/taro' import { Provider } from '@tarojs/redux' import configStore from './store' import Index from './pages/index' import './app.scss' const store = configStore() class App extends Component { ... render () { return ( <Provider store={store}> <Index /> </Provider> ) } }

constants文件夹来定义一系列所需的action type常量

//constants/login.js
 
export const LOGIN_TYPE = "login_type"

然后开始创建处理指令的reducers

// reducers/index.js
 
import { combineReducers } from 'redux'
import login from "./login"

export default combineReducers({
  login
})
// reducers/login.js

import {LOGIN_TYPE} from "../constants/login"
const INITIAL_STATE = {
  loginType: false
}

export default function login (state = INITIAL_STATE, action) {
  switch (action.type) {
    case LOGIN_TYPE:
      return {
        ...state,
        loginType: action.data
      }
    default:
      return state
  }
}

接着在actions中定义函数对应的指令。

//actions/login.js

import {LOGIN_TYPE} from "../constants/login"
 
export const loginTypeFun = (data) => {
 return {
  type: LOGIN_TYPE,
  data: data
 }
}

 最后实现数据状态的改变

//pages/index/index.js

import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtButton } from "taro-ui"
import './index.scss'
import { connect } from '@tarojs/redux'
import { loginTypeFun } from '../../actions/login'

@connect(({ login }) => ({
  login
}), (dispatch) => ({
  changeLoginType(data) {
    dispatch(loginTypeFun(data)})
  }
}))

class Index extends Component {
  constructor () {
    super(...arguments)
    this.state = ({
      
    })
  }
  
  config = {
    navigationBarTitleText: '首页'
  }

  componentWillMount() { }

   toChangeLogin = (e) => {
       this.props.changeLoginType(true)
    }
  }

  render () {
    return (
      <View className='index'>
        {this.props.login.loginType}
        <AtButton type="primary" onClick={this.toChangeLogin}>改变状态loginType</AtButton>
      </View>
    )
  }
}

export default Index

 输出结果true

猜你喜欢

转载自www.cnblogs.com/juewuzhe/p/11105960.html