關(guān)于redux的重要性我就不再詳細(xì)講解讯榕,直接進(jìn)入今天的正題久锥,添加redux到自己的項(xiàng)目中
-
react-native init Reading_Redux 初始化一個(gè)rn項(xiàng)目家淤,目錄結(jié)構(gòu)如下其中app是我手動(dòng)添加的
WX20170105-135339.png 新建redux文件夾,同時(shí)在其下創(chuàng)建actions瑟由、constant絮重、containers、reducer歹苦、store文件夾绿鸣,用處稍后會(huì)講解。
3.創(chuàng)建index.js
......
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
/** state,add,del是哪里來(lái)的暂氯?不要急 **/
const {state}=this.props;
const {add,del,init}=this.props.actions;
return (
<View style={styles.container}>
<Text>Redux-加法運(yùn)算</Text>
<View style={styles.item}>
<Text>合 計(jì):</Text>
<Text style={{color: 'red'}}>{state.sum}</Text>
</View>
<View style={[styles.item, {top: 10}]}>
<TouchableWithoutFeedback onPress={add} >
<View style={styles.touch}>
<Text style={styles.but}>+</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback onPress={del}>
<View style={styles.touch}>
<Text style={styles.but}>-</Text>
</View>
</TouchableWithoutFeedback>
</View>
</View>
);
}
}
......
看注釋潮模、看注釋、看注釋
4.在actions中創(chuàng)建IndexAction.js
import * as types from '../constant/ActionTypes';
//數(shù)量加
export function add() {
return {
type: types.INDEX_ADD
}
}
//數(shù)量減
export function del() {
return {
type: types.INDEX_DEL
}
}
原來(lái)是add和del在這里做了定義痴施,不難看出每個(gè)fun都return了一個(gè)常量type擎厢,接下來(lái)我們就來(lái)創(chuàng)建接受這個(gè)type值的類IndexReducer.js
5.在reducer中創(chuàng)建IndexReducer.js
import * as types from '../constant/ActionTypes';
const initialState = {
sum:0
};
export default function IndexReducer(state = initialState, action = {}) {
switch (action.type){
case types.INDEX_ADD:
return {
...state,
sum:state.sum+1
};
break;
case types.INDEX_DEL:
return {
...state,
sum:state.sum-1
};
break;
case types.INDEX_INIT:
return {
...state,
sum:action.param!=undefined
};
break;
default:
return state;
}
}
我們可以看到真正的邏輯操作是在這里完成的,根據(jù)不同的type值我們處理了sum的結(jié)果并且return了出去辣吃,想想index.js中我們顯示的最終結(jié)果是不是sum动遭,原來(lái)它是定義在這里的,到此為止index中我們的那個(gè)疑問都有了結(jié)果神得,可是這些都是如何連接在一起的厘惦?接下來(lái)我們就開始redux的重點(diǎn),綁定state到我們自己的頁(yè)面哩簿。
這里還有一種方式就是將所有的邏輯操作放在我們的action中宵蕉,然后將結(jié)果和type一起返回酝静,然后在reducer中只是接受值并且return就可以了。
6.創(chuàng)建狀態(tài)收集類RootReducer.js
import { combineReducers } from 'redux';
import IndexReducer from './IndexReducer';
const RootReducer = combineReducers({
IndexReducer,
/** 添加其他自己定義好的reducer **/
});
export default RootReducer;
如果你覺的這段代碼理解起來(lái)有點(diǎn)抽象羡玛,你可以把他理解為有一個(gè)樹??别智、而每一個(gè)reducer就是一個(gè)枝干,這個(gè)類就是將所有的枝干連接到主干的一個(gè)過程稼稿。這是一個(gè)固定格式直接copy也是可以的薄榛。
7.上一步我們創(chuàng)建出了狀態(tài)收集類或樹,這一步我們就把這個(gè)樹種植到某一塊區(qū)域讓他茁壯成長(zhǎng)让歼,這個(gè)地方就是redux的store敞恋。
新建configure-store.js
import {createStore, applyMiddleware} from 'redux';
import rootReducer from '../reducer/RootReducer';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const createLogger = require('redux-logger');
/** 在開發(fā)者模式下開啟打印日志功能**/
if (process.env.NODE_ENV === 'development') {
const logger = createLogger();
//redux 日志打印
middlewares.push(logger);
}
const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore);
/**創(chuàng)建configureStore方法,開辟一塊空地store谋右,同時(shí)把樹rootReducer種植進(jìn)去耳舅,initialState為初始狀態(tài)**/
export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState);
return store;
}
到此redux算是配置完成了,接下來(lái)我們將這個(gè)樹指定到我們的項(xiàng)目中倚评,同時(shí)將每一個(gè)枝干和我們的頁(yè)面做關(guān)聯(lián)浦徊。
8.在Root.js中將store綁定到我們的項(xiàng)目中
......
import { Provider } from 'react-redux';
import IndexContainer from './redux/containers/IndexContainer';
import configureStore from './redux/store/configure-store';
const store =configureStore();
const Root = () => (
<Provider store={store}>
<IndexContainer />
</Provider>
);
export default Root;
9.在IndexContainer中綁定IndexReducer、IndexAction到我們的index頁(yè)面
......
import Index from '../../pages/Index';
import {bindActionCreators} from 'redux';
import * as IndexAction from '../actions/IndexAction';
class IndexContainer extends React.Component {
render() {
return (
<Index
{...this.props}
/>
);
}
}
/** 綁定IndexReducer天梧、IndexAction **/
export default connect(state => ({
state: state.IndexReducer
}),
(dispatch) => ({
actions: bindActionCreators(IndexAction, dispatch)
})
)(IndexContainer);
這樣index中的的疑問就徹底解決了盔性,是不是很開森。
總結(jié)一下:其實(shí)redux的使用并沒有那么難呢岗,伙伴們照著我的這幾個(gè)步驟走下來(lái)就可以了冕香,對(duì)于redux的實(shí)現(xiàn)原理我會(huì)在之后的文章中具體介紹。
最后我把我的package.json中的代碼也貼出來(lái)
{
"name": "Reading_Redux",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"react": "15.4.1",
"react-native": "0.40.0"
},
"devDependencies": {
"react-redux": "^4.4.5",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.1.0"
}
}
項(xiàng)目地址:GitHub
博主QQ小窩后豫、期待你的到來(lái) 581621024