react-redux的使用简介
概述
redux是专门做状态管理的JS库,它并非一定要跟react配合使用,你也可以用在Vue项目中。我们主要用它来传递组件之间的数据和状态,方便我们进行组件状态的集中管理
基本原理如上,store是唯一的,你可以简单的理解成一颗树或者是特殊的js数据库,所有的数据统一放在store里面,如果需要改变store的值,就要派发action对象,然后通知dispatch进行分发,reducer负责进行具体的修改,store改变,组件监听到,进行组件重新渲染。
应用
Reducer 根据action提交的操作进行具体的修改,state是只读的,修改state唯一方法就是触发action,然后返回一个新的state给store
import {createStore} from 'redux'; const countReducer = (state = {count:1},action) =>{ switch (action.type){ case 'COUNT_ADD': return {...state,count:state.count + 1}; default: return state; } } const store = createStore(countReducer); //单一数据源,可以帮助我们创建一个store // 派发action store.dispatch({ type:'COUNT_ADD' }); console.log(store.getState());//获取store里面所有的数据内容
以上就是一个简单的redux执行流程,并不涉及到react,如果有多个redux,需要用combineReducers进行合并,然后放置到store内
React-redux
react-redux提供两个常用api,Provider和connect,组件共享的数据从Provider这个顶层组件通过props传递,store须作为参数属性放到Provider组件中去,而connect则提供了组件获取store中数据
post_reducer
const postReducer = (state = {list:[{id:1,title:'Hello World'}]},action) =>{ switch (action.type){ case 'LOAD_POSTS': return {...state,list:action.payload}; default: return state; } } export default postReducer;
我们从在线json获取一些测试值 post_api
import {get} from 'axios'; export function getPosts() { return get('https://jsonplaceholder.typicode.com/posts'); }
post_action 异步请求获取值
import {getPosts} from '../services/post_api'; export const loadPostsAction = async (dispatch) =>{ const res = await getPosts(); dispatch({ type:'LOAD_POSTS', payload:res.data }) }
store储存
const store = createStore(postReducer);
export default store;
Provider通过props传递
import React from 'react'; import ReactDom from 'react-dom'; import store from './store'; import {Provider} from 'react-redux'; import PostList from './components'; class Entry extends React.Component{ render(){ return <PostList/> } } //通过provider把redux和react连接,store传递到react项目中 ReactDom.render(<Provider store={store}><Entry/></Provider>,document.getElementById('root'));
component组件 PostList 将值加载到页面上
import React,{Component} from 'react'; import {connect} from 'react-redux'; import {loadPostsAction} from '../action/post_action'; import { List, Typography } from 'antd'; import 'antd/dist/antd.css'; class PostList extends Component{ constructor(props){ super(props); } componentDidMount(){ this.props.dispatch(loadPostsAction); } render(){ const {list} = this.props.post; return (<List header={<div>Header</div>} footer={<div>Footer</div>} bordered dataSource={list} renderItem={item => ( <List.Item> <Typography.Text mark>[ITEM]</Typography.Text> {item.title} </List.Item> )} />) } } const mapStateToProps = (state)=>{ //将state的值转换成props return { post:state.post } } //通过connect连接组件和redux数据,传递state数据到dispatch方法 export default connect(mapStateToProps)(PostList);