Redux 分為store,reducers,action,話不多說直接貼代碼。
首先是reducers中定義一些type鍵,用于reducers處理狀態
const LOGIN = 'LOGIN';
const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_FAIL = 'LOGIN_FAIL';
然后就是reducers的純函數
const initialState = {
isLoginIn: false,
userInfo: {},
msg: ''
};
export default function loginReducer (state = initialState, action) {
switch (action.type) {
case LOGIN:
return {
...state,
isLoginIn: false,
userInfo: {}
};
case LOGIN_SUCCESS:
console.log('LOGIN_SUCCESS');
console.log(action);
return {
...state,
isLoginIn: true,
userInfo: action.userInfo
};
case LOGIN_FAIL:
console.log('LOGIN_FAIL');
console.log(action);
return {
...state,
isLoginIn: false,
};
default:
return state;
}
};
initialState 是初始狀態,是你需要用到的一些數據或者狀態,type里面是狀態更新...state 復制一份state,一般不在原state上做更改。
/**
* action: login
*/
export function performLoginAction(username, password) {
return (dispatch) => {
dispatch({'type': LOGIN})
Util.post(API.LOGIN,{'phone':username,'password':password},function(ret){
console.log(ret);
if (ret.code == 200) {
dispatch({'type': LOGIN_SUCCESS, userInfo: ret.data, msg: ret.msg,isLoginIn: true})
}else {
dispatch({'type': LOGIN_FAIL, msg: ret.msg, isLoginIn: false})
}
})
}
}
這里就是一個action,就是一個網絡請求,對請求結果進行處理,成功或者失敗都使用dispatch分發處理type,給state賦值。這里就是一個reducer的內容,其實是把action和reducer合在一起進行處理。
接下來就是store 完全的復制粘貼就可以了
'use strict';
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './Reducers/reducers';
const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
export default function configureStore(initialState) {
const store = createStoreWithMiddleware(rootReducer, initialState);
return store;
}
需要注意的是rootReducer是所有的reducer的合集,下面只是一個reducer,創建多個reducer也是在這塊寫。
import {combineReducers} from 'redux';
import LoginReducer from './login';
const rootReducer = combineReducers({
login: LoginReducer,
});
export default rootReducer;
store寫完之后,就要去程序根js中嵌套,
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {Provider} from 'react-redux'
import Root from './src/Component'
import configureStore from './src/Redux/creat'
const store = configureStore();
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Root />
</Provider>
)
}
}
打工是不可能的.gif