react-redux的简单使用
来源:互联网 发布:淘宝卖家电话人工服务 编辑:程序博客网 时间:2024/05/17 07:06
正式接触react应该有两个月了,项目开始也有一个月了,
开始新项目的时候就没有打算使用redux,因为感觉学习这个的成本挺高.
这两天,项目第一版已经出来了,昨天下午有时间就抓紧时间看看redux相关的东西,大致有个了解,然后今天就照葫芦画瓢,把一个模块给整理了下,换成了redux.
在这里记录下使用,以备后需.
react-redux
使用前得需要安装
npm i --save react-redux redux redux-thunk
- 先创建actions
获取用户列表的相关操作.
// src/actions/users/index.jsimport * 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.jsimport { message } from 'antd';const API_URL = process.env.REACT_APP_DEV_API_URLvar 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: }}
- 创建constants
// src/constants/users/ActionTypes.jsexport const QUERY_USERS = 'QUERY_USERS'export const QUERY_USERS_SUCCESS = "QUERY_USERS_SUCCESS"
- 创建 reducers相关
// src/reducers/users.jsimport {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.jsimport { combineReducers } from 'redux'//BASE APIimport users from './users'const rootReducer = combineReducers({ users,})export default rootReducer
这里创建了相关的reducers.
- 在根组件store
// src/index.jsimport 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.jsimport {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;}
- connect
// src/components/User.jsimport * 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写了请求接口的方法,觉得不是很规范,后需会改进.
阅读全文
0 0
- react-redux的简单使用
- 实现简单的 react-redux
- react-native 简单的react-redux创建
- react中react-redux和react-router4.*的配合使用
- 使用Redux管理你的React应用
- 使用Redux管理你的React应用
- 使用Redux管理你的React应用
- [React Native]Redux的基本使用方式
- [React Native]Redux的基本使用方式
- React-Native Redux的基本使用方式
- React-redux使用
- react-redux使用实例
- react-redux使用小结
- 使用React-Redux感悟
- react-redux使用小结
- redux react使用
- React和Redux的连接react-redux
- React和Redux的连接react-redux
- Rn学习
- 学习廖大的JS--第二节
- __metaclass__
- 记一次MySQL中Waiting for table metadata lock的解决方法
- 辗转相除法
- react-redux的简单使用
- Unit7
- Spring MVC @Validated的使用
- 十一月二号课堂笔记
- 并发学习路线
- android java8的使用配置
- Lock与synchronized 的区别
- Java笔记第十一课(String类&StringBuffer类)
- bzoj 3039: 玉蟾宫(悬线法)