模块化目录结构
action 属于Reduex, 是把数据从应用传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch()
将 action 传到 store。
https://www.jianshu.com/p/ad7eddb23d66
connect属于react-redux
import {connect} from 'react-redux'
import Counter from '../component/count'
//将state绑定到props的counter
const mapStateToProps = (state)=> {
console.log(state);
return {
counter: state
}
};
//将action的所有方法绑定到props上
const mapDispatchToProps = (dispatch) => {
return {
onAdd: ()=> {
dispatch({type: "INCREMENT_COUNTER"});
},
onCut: ()=> {
dispatch({type: "DECREMENT_COUNTER"});
}
};
};
//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
actionCreators.js
import * as constants from './constants'; export const handleChange = (action) => ({ type: constants.CHANGE_NUM, num:action.num, index:action.index })
constants.js
export const CHANGE_NUM = 'car/CAR_CHANGE_NUM';
store/index.js
import reducer from './reducer'; import * as actionCreators from './actionCreators'; import * as constants from './constants'; export {reducer,actionCreators,constants}
reducer.js
import * as constants from './constants'; import { fromJS } from 'immutable'; const defaultState = fromJS({ goodslist:[ { id:1, num:1, name: '范范木门01测试-卢', text: '"A款橡木","A款橡木","A款橡木"', monery: 100, url:'https://fc6b2827-b381-4383-9079-fa34f41768e3' } ] }); const changeGoodsNum=(state, action) => { console.log(action) // return state.merge(`goodslist[${action.index}]`, action.num); // state.set('showScroll', goodslist); }; export default (state = defaultState, action) => { switch (action.type) { case constants.CHANGE_NUM: { // console.log(state.toJS()) const {goodslist } = state.toJS(); console.log(goodslist) goodslist[action.index].num = action.num>0?action.num:1; state.set('goodslist', fromJS(goodslist)); console.log(goodslist) return state.set('goodslist', fromJS(goodslist)) } // case constants.CHANGE_NUM: // return changeGoodsNum(state, action); default: return state; } }
immutable在redux中的应用
https://www.jianshu.com/p/3e162080711b
https://www.cnblogs.com/greatluoluo/p/8469224.html
https://www.jianshu.com/p/5718c917d701
https://github.com/immutable-js/immutable-js
https://www.cnblogs.com/PrayLs/p/10506886.html
1、什么是Immutable?
Immutable是一旦创建,就不能被更改的数据。对Immutable对象的任何修改或添加删除操作都会返回一个新的Immutable对象。Immutable实现的原理是Persistent Data Structure(持久化数据结构),也就是是永久数据创建新数据时,要保证旧数据同时可用且不变。同时为了避免deepCopy把所有节点都复制一遍带来的性能损耗,Immutable使用了Structural Sharing(结构共享),即如果对象树结点发生变化,只修改这个结点和受它影响的父节点,其他结点进行共享。
const mapState = (state) => ({ goodslist: state.getIn(['cars', 'goodslist']) }); //getIn(['cars', 'goodslist'])
const mapDispatch = (dispatch) => ({ handleChange(index,e) { console.log(index,'index') console.log(e.target.value,'num') dispatch(actionCreators.handleChange({ index:index, num:e.target.value })) }, }); export default connect(mapState, mapDispatch)(Car);