$ npx create-react-app react-immutable
$ yarn add redux immutable react-redux redux-immutable
import React, { Component } from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import actionCreators from '../store/count/actionCreators';
class Button extends Component{
render(){
return(
)
}
}
export default connect(
state => ({
count: state.getIn(['count'])
}),
dispatch => bindActionCreators(actionCreators,dispatch)
)(Button) // 在button组件外生成一个容器组件,将外层的属性和方法传递给内部的ui组件
import React, { Component } from 'react'
import {connect} from 'react-redux'
class Content extends Component{
render(){
return(
count: { this.props.count.get('count')}
)
}
}
export default connect(
state => ({
count: state.getIn(['count'])
})
)(Content)
index.js文件用来打造store
import {createStore} from 'redux';
import reducers from './reducers'
const store = createStore(reducers)
export default store
reducers.js文件用来管理分片的reducers
import { combineReducers} from 'redux-immutable'; // 这里是从redux-immutable引用的combineReducers
import count from '../store/count/reducers'
const reducers = combineReducers({
// 分片的reducers
count
})
export default reducers
import { Map } from 'immutable'
const state =Map({
count:0
})
export default state
import * as type from './type'
const actionCreators = {
increment(){
// 创建动作
const action = {
type: type.INCREMENT
}
// 发送动作
return action // 这里动作的发送由dispatch帮我们做了 所以只要返回action就可以了
}
}
export default actionCreators
export const INCREMENT = 'increment'
import state from './state'
import * as type from './type'
const reducers = (newState=state,action) => {
switch (action.type) {
case type.INCREMENT:
return newState.set('count',newState.get('count')+1) // Immutable方法用get来获取数据 用set来设置数据
break;
default:
return newState
break;
}
}
export default reducers
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './store'
import {Provider} from 'react-redux'
ReactDOM.render(
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
export default connect(
state => ({
count: state.getIn(['count'])
})
)(Content)
count: { this.props.count.get('count')}
export default connect(
state => ({
count: state.getIn(['count'])
}),
dispatch => bindActionCreators(actionCreators,dispatch)
)(Button)