使用redux 需要先明白store、action、reducer三个概念的定义
store 就是用来放置各种状态的仓库 action 就是一个动作对象 {type:’’,data:’’} reducer 本质就是一个处理动作对象的函数,具有初始化状态的更新状态的功能
1.store.js的写法
/*
* createStore方法用来创建一个store
* 引入reducers集合作为createStore的第一个入参
* 传入applyMiddleware(thunk)作为createStore的第二个入参,作用是用来解决异步action
*/
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import reducers from './reducers'
export default createStore(reducers,applyMiddleware(thunk))
2.reducers.js的写法
//使用combineReducers合并reducer
import {combineReducers} from 'redux'
const reducers = combineReducers({
//登录态reducer
loginState:(preState=false,action)=>{
switch (action.type) {
case 'login':return action.data
default:return preState
}
},
//用户权限reducer
authorityState:(preState={name:'使用者'},action)=>{
switch (action.type) {
case 'authority':return action.data
default:return preState
}
}
})
export default reducers
3.actions.js的写法
/*
* action 本质是个动作对象,是reducer的第二个入参
*/
//登录态action
export const loginAction = (data)=>{
return {type:'login',data}
}
//用户权限action
export const authorityAction = (data)=>{
return {type:'authority',data}
}
4.入口文件index.js的写法
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
//注意Provider很重要,用来给每个容器组件传递一个store,并监控redux中状态的变化并重新渲染组件,这就是react-redux的好处
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root'))
5.app.js的写法
//因为是个简单的Demo,所有就简单写一下
import React, { Component } from 'react'
import Login from './components/Login'
export default class App extends Component {
render() {
return (
<div>
<Login/>
</div>
)
}
}
6.组件中的使用
这里写了一个UI组件Login 通过connect方法和容器组件关联起来,因为react-redux 不允许UI组件直接调用redux里的状态和各种方法只能通过容器组件的props来传递
import React, { Component } from 'react'
import {connect} from 'react-redux'
//这里引入了actions.js中定义好的动作对象
import {loginAction,authorityAction} from '../../redux/actions'
class Login extends Component {
//调用修改登录后的状态为true
loginIn =()=>{
this.props.loginDispatch(true)
this.props.authorityDispatch({name:'管理员'})
}
//调用修改登出后的状态为false
loginOut =()=>{
this.props.loginDispatch(false)
this.props.authorityDispatch({name:'使用者'})
}
render() {
return (
<div>
<h2>redux,react-redux Demo</h2>
<hr />
<h3>当前是{this.props.login ?'登入':'登出'}状态</h3>
<h3>当前是{this.props.authority.name}权限</h3>
<button onClick={this.loginIn}>登入</button>
<button onClick={this.loginOut}>登出</button>
</div>
)
}
}
export default connect(
//注意此处是方法mapStateToProps方法的简写,接收redux中的状态对象集合state,本质是传递redux中的状态给UI组件
state => ({
login:state.loginState,
authority:state.authorityState
}),
//注意此处是方法mapDispatchToProps方法的简写,接收redux中的dispatch方法,本质是传递redux中reducer方法给UI组件
{
loginDispatch:loginAction,
authorityDispatch:authorityAction
}
)(Login)