1. 程式人生 > >react-redux的簡單使用

react-redux的簡單使用

正式接觸react應該有兩個月了,專案開始也有一個月了,
開始新專案的時候就沒有打算使用redux,因為感覺學習這個的成本挺高.
這兩天,專案第一版已經出來了,昨天下午有時間就抓緊時間看看redux相關的東西,大致有個瞭解,然後今天就照葫蘆畫瓢,把一個模組給整理了下,換成了redux.
在這裡記錄下使用,以備後需.

react-redux

使用前得需要安裝

npm i --save react-redux redux redux-thunk
  1. 先建立actions
    獲取使用者列表的相關操作.
// src/actions/users/index.js
import * as usersTypes from '../../constants/users/ActionTypes'
; export const queryUsersSuccess = users => ({ type: usersTypes.QUERY_USERS_SUCCESS, users }) export const queryUsers = () => { return dispatch => { MyFetch.get(`v1/users`).then(data => { dispatch(queryUsersSuccess(data.users)) }) } }
// MyFetch.js
import { message } from 'antd'
; const API_URL = process.env.REACT_APP_DEV_API_URL var Fetch = { get(path) { return new Promise((resolve, reject) => { fetch(`${API_URL}/${path}`, { headers: new Headers({ 'token': localStorage.getItem("my-custom-token"), 'Accept'
: 'application/json', 'Content-Type': 'application/json', }) }).then(res => { return handleStatus(res); }) .then(json => { resolve(json); }) .catch(err => { reject(err); }); })
; }, post(params) {}, ... } function handleStatus(res) { let errors; switch (res.status) { case 200: return res.json(); case 500: console.log("500錯誤"); message.error('伺服器內部錯誤', 5) errors = `${res.status}, ${res.statusText}` throw errors case 404: message.error("資源不存在", 5) errors = `${res.status}, ${res.statusText}` throw errors case 401: message.error("登入會話過期,請重新登入", 5) localStorage.removeItem("my-custom-token") window.location.href = '/login' break; case 403: message.error("無許可權訪問", 5) errors = `${res.status}, ${res.statusText}` throw errors default: } }
  1. 建立constants
// src/constants/users/ActionTypes.js
export const QUERY_USERS = 'QUERY_USERS'
export const QUERY_USERS_SUCCESS = "QUERY_USERS_SUCCESS"
  1. 建立 reducers相關
// src/reducers/users.js
import {QUERY_USERS_SUCCESS} from "../constants/users/ActionTypes";

const initState = {
  users: []
}

export default function users(state = initState, action) {
    console.log("Welcome to reducer users");
    switch (action.type) {
        case QUERY_USERS_SUCCESS:
          return {
            ...state,
            users: action.users
          }
        default:
            return state
    }
}
// src/reducers/index.js
import { combineReducers } from 'redux'

//BASE API
import users from './users'

const rootReducer = combineReducers({
  users,
})

export default rootReducer

這裡建立了相關的reducers.

  1. 在根元件store
// src/index.js
import React from 'react';
import { Provider } from 'react-redux'
import configureStore from './configureStore';
import ReactDOM from 'react-dom';
import App from './App';
const store = configureStore()

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
// src/configureStore.js
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';

// let store = createStore(combineReducers);

export default function configureStore() {
    const store = createStore(
        rootReducer,
        applyMiddleware(thunkMiddleware)
    );

    return store;
}
  1. connect
// src/components/User.js
import * as UserActions from '../../actions/users';
...
class User extends Component{
  componentDidMount(){
       this.props.actions.queryUsers();
  }
}

const mapStateToProps = state => ({
  company: state.companies,
    users: state.users //這個是reducers定義的
})

const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(UserActions, dispatch)
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Company)

這樣就可以使用啦.

本文原文

ps: 目前看來,這個方法很low. 在action寫了請求介面的方法,覺得不是很規範,後需會改進.