首先需要安装redux,react-redux,babel-plugin-transform-decorators-legacy
babel-plugin-transform-decorators-legacy是什么?
他是用来支持@写法的
安装完以后在.babelrc里面设置
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-decorators-legacy"]
}
}
}
首先创建一个redux,我们就取名为num.redux.js
内容为
const ADD_TEM="升温";
const initState={
number:20
}
export function num(state=initState,action) {
switch (action.type){
case "升温":
return {...state,number:state.number+1}
default:
return state;
}
}
export function addTem() {
return {type:ADD_TEM};
}
然后创建一个reducer,把reducer函数去过来,交给combineReducers管理
import {combineReducers} from "redux";
import {num} from "./redux/num.redux";
export default combineReducers({num});
现在开始写自己的文件,我们新建container文件夹,新建文件Temp.js
内容为
import React,{PureComponent} from "react";
import {View,Text,Button} from "react-native";
import {connect} from 'react-redux';
import {addTem} from "../redux/num.redux";
@connect(state=>state.num,{addTem})
export default class Temp extends PureComponent{
render(){
return (
现在温度{this.props.number}
)
}
}
我们在App.js里面引入redux,react-redux,reducer,并写成如下的样子,在里面引入Temp即可
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import {createStore} from "redux";
import {Provider} from "react-redux";
import reducer from "./reducer";
import Temp from "./container/Temp";
const store=createStore(reducer)
export default class App extends Component {
render() {
return (
(
)
);
}
}
redux只能处理同步,要处理异步我们还要添加redux-thunk中间件
npm install redux-thunk --save-dev
然后使用applyMiddleware开启thunk中间件
到这里reactnative引入redux基本就大工告成
如果有什么问题,欢迎大家给我留言
react-native整合系列(二)——集成Ant Design Mobile RN https://www.jianshu.com/p/f8b6a07e108f
react-native整合系列(三)——集成react-native-router-flux https://www.jianshu.com/p/35cdf1237017