react-redux 经典案例

1,668 阅读2分钟

在学习了redux基本教程后,课程参考如下网址:www.redux.org.cn/docs/introd…

核心概念: 1.整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中 2.唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象 3.使用纯函数来执行修改。为了描述 action 如何改变 state tree ,你需要编写 reducers

那么问题来了,action是怎么和store联系起来的呢? 核心中的核心: 每当 dispatch action 时,store 的 state 会被立即更新,关键字,dispatch。

那他是怎么更新的呢? store 里面使用 createStore(reducer), 参数render为 根据具不用action 返回不同的state的 reducer的函数,

connect是连接组件和store的功能,两个参数,都是函数 第一个参数 mapStateToProps 允许我们将store的数据以props 绑定到组件,这个利于组件获取最小属性,而不是获取全部store里面的数据, 参数是store里面的数据state

第二个参数 mapDispatchToProps 参数是 dispatch,将 action 作为 props 绑定到组件上。关键字,action

首先connect之所以会成功,是因为Provider组件: 在原应用组件上包裹一层,使原来整个应用成为Provider的子组件 接收Redux的store作为props,通过context对象传递给子孙组件上的connect

redux-soga其实就是能触发dispatch action 的独立进程,其实redux-thunk 集合 async await 已经足够

1.首先编写一个actions

export const CHANGE_VALUE = 'CHANGE_VALUE';

function infoInputChange(data) {
return (dispatch) => {
dispatch({
type: CHANGE_VALUE,
data: {
...data,
},
});
};
}


export { infoInputChange };

2.编写一个reducers

import * as actions from '../actions/patient.js';

const initialState = {
patientSelectedRowKeys: [],
};

export default function index(state = initialState, action = {}) {
switch (action.type) {
case actions.CHANGE_VALUE:
return Object.assign({}, state, {
patientSelectedRowKeys: action.data,
});
default:
return state;
}
}

3.在reducers 的index.js中填加如下内容

import { combineReducers } from 'redux';
import patient from './patient';

// 将现有的reduces加上路由的reducer
const rootReducer = combineReducers({
patient,

// routing: routerReducer,
});

export default rootReducer;

4.在使用的组件存取中要先引入

import { connect } from 'react-redux';
import * as actions from '@actions/patient.js';
//取store数据时候用
const { PatientTableState = {} } = this.props;
const patientSelectedRowKeys = PatientTableState.patientSelectedRowKeys.patientSelectedRowKeys;
//数据变更后存数据用
this.props.dispatch(actions.infoInputChange({
patientSelectedRowKeys: ids,
}));
 
export default connect((state) => {
return {
PatientTableState: state.patient,
};
})(PatientTable);