简介
在 Taro
中可以自由地使用 React
生态中非常流行的数据流管理工具 Redux
来解决复杂项目的数据管理问题。
以下是项目中<font color="red"> 结构最简化 </font>的实例效果,完整结构请参考官方文档
安装中间件
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
三个文件
[图片上传失败...(image-cecf68-1637047670199)]
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, action) => {
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>
)
}
}