0
点赞
收藏
分享

微信扫一扫

Taro中使用Redux ( 结构最简 )


Taro中使用Redux ( 结构最简 )_taro Redux

文章目录

  • ​​简介​​
  • ​​安装中间件​​
  • ​​新建store目录​​
  • ​​index.js​​
  • ​​actions.js​​
  • ​​reducer.js​​
  • ​​引入Store​​
  • ​​使用Redux​​

简介

在 ​​Taro​​​ 中可以自由地使用 ​​React​​​ 生态中非常流行的数据流管理工具 ​​Redux​​ 来解决复杂项目的数据管理问题。

以下是项目中 结构最简化 的实例效果,完整结构请参考​​官方文档​​

安装中间件

​yarn add redux react-redux redux-thunk redux-logger​​​ 或
​npm install --save redux react-redux redux-thunk​

新建store目录

在项目 ​​src​​​ 目录下新增一个 ​​store​​​ 目录,并新增​​index.js​​​、​​actions.js​​​、​​reducer.js​​三个文件

Taro中使用Redux ( 结构最简 )_Redux_02

index.js

​创建唯一的store​

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

// window.__REDUX_DEVTOOLS_EXTENSION__ 可使用Redux DevTools插件
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

// 使用Redux-thunk中间件
const enhancer = composeEnhancers(applyMiddleware(thunk));

// 创建store
const store = createStore(reducer, enhancer);

export default store;

actions.js

​action的统一管理​

export const add = () => {
return {
type: 'ADD'
}
}

export const minus = () => {
return {
type: 'MINUS'
}
}

// 异步的action
export function asyncAdd () {
return dispatch => {
setTimeout(() => {
dispatch(add())
}, 2000)
}
}

reducer.js

import { combineReducers } from 'redux';

const defaultState = {
num: 0
}

const counter = (state = defaultState,) => {
switch (action.type) {
case 'ADD':
return {
...state,
num: state.num + 1
}
case 'MINUS':
return {
...state,
num: state.num - 1
}
default:
return state
}
}

export default combineReducers({ counter });

引入Store

在项目 ​​src​​​ 目录下找到​​app.js​​​或​​app.jsx​

import { Component } from 'react';
import { Provider } from 'react-redux';
import store from './store';
import './app.scss';

class App extends Component {
render () {
return (
<Provider store={store}>
{this.props.children}
</Provider>
)
}
}

export default App;

使用Redux

业务组件中使用​​Redux​

import { Component } from "react";
import { connect } from 'react-redux';
import { View, Button, Text } from '@tarojs/components';
import { add, minus, asyncAdd } from '../../store/actions';
import "./index.scss";

@connect(({ counter }) => ({ counter }), (dispatch) => ({
add () {
dispatch(add());
},
dec () {
dispatch(minus());
},
asyncAdd () {
dispatch(asyncAdd());
}
}))

export default class User extends Component {

componentWillReceiveProps (nextProps) {
console.log(this.props, nextProps);
}

constructor() {
super(...arguments);
this.state = {};
}

render () {
const { add, dec, asyncAdd, counter } = this.props;
return (
<View>
<Button onClick={add}>+</Button>
<Button onClick={dec}>-</Button>
<Button onClick={asyncAdd}>async</Button>
<View><Text>{counter.num}</Text></View>
</View>
)
}

}


举报

相关推荐

0 条评论