1.安装antd
npm install antd --save
2.安装redux
npm install redux --save
3.redux devtools调试工具安装
3.1 安装插件
redux devtools插件安装
3.2在store仓库中添加代码
createStore函数调用的地方,给它加第二个参数 window.REDUX_DEVTOOLS_EXTENSION && window.REDUX_DEVTOOLS_EXTENSION()
4.使用步骤
1、2、3、4均存储在store文件夹下
Redux
1)引入createStore,创建仓库(增强函数不写也行)
import {createStore, applyMiddleware, compose} from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancer(applyMiddleware(thunk))
const store = createStore(reducer,enhancer)//增强函数
export default store;
2)创建reducer
import {CHANGE_INPUT, ADD_ITEM, DELETE_ITEM, GET_LIST} from './actionTypes'
const defaultState = {
inputValue : 'Write something',
list:[
'xxxxx',
'ccccccc',
'vvvvvvv'
]
}
export default (state = defaultState,action) =>{
//Reducer里只能接受state,不能改变state
if(action.type === CHANGE_INPUT){
let newState = JSON.parse(JSON.stringify(state))//深度拷贝
newState.inputValue = action.value//必须是纯函数,即必须为aciton传的值
return newState
}
return state;
}
3)可把方法类单独写
export const CHANGE_INPUT = 'changeInput'
4)可把方法单独写
import {CHANGE_INPUT, ADD_ITEM, DELETE_ITEM, GET_LIST} from './actionTypes'
export const changeInputAction = (value)=>({
type:CHANGE_INPUT,
value
})//({})形式返回里面的对象
5)获取、传递值
this.state = store.getState();//获取数据
const action= (value)=>({
type:CHANGE_INPUT,
value
})
store.dispatch(action)//传递action
6)订阅
store.subscribe(this.storeChange)//订阅了state的值才会改变
storeChange(e){
this.setState(store.getState())
}
react-redux(基于redux)
1)安装
npm install --save react-redux
2)提供器Provider
import {Provider} from 'react-redux'//提供器
const App = (
<Provider store={store}>
<TodoList />
</Provider>
)
ReactDOM.render(
<App />,
document.getElementById('root')
);
3)connect连接器(还未写dispatch)
const stateToProps = (state)=>{
return{
inputValue:state.inputValue
}
}
export default connect(stateToProps,null)(TodoList)
4)获取值
不用this.state.xx改为this.props.xx
5)方法
const dispatchToProps = (dispatch)=>{
return {
inputChange(e){
let action = {
type:'change_input',
value:e.target.value
}
dispatch(action)
}
}
}
export default connect(stateToProps,dispatchToProps)(TodoList)
6)不用this.state.inputChange改为this.props.inputChange(不用绑定)