redux:提供给应用一个全局的状态,必须按照它的方式单向数据流方式修改状态
核心概念:
1,state就是一个状态对象
2,action就是动作,用来触发reducer函数
3,reducer是一个函数,用来修改state
模块化store结构
state.js
const state = {
info: {
age: 20,
sex: '男',
money: 10000
}
}
export default state
actions.js
import { store } from './store';
// actions 所有的动作,dispatch会触发redcuer
const actions = {
addMoney (payload) {
store.dispatch(
{
type: 'addMoney',
payLoad: payload
}
)
},
subMoney (payload) {
store.dispatch(
{
type: 'subMoney',
payLoad: payload
}
);
},
addAge (payload) {
store.dispatch(
{
type: 'addAge',
payLoad: payload
}
);
},
subAge (payload) {
store.dispatch(
{
type: 'subAge',
payLoad: payload
}
);
}
}
export default actions;
/*
*/
reducer.js
import _state from './state.js'
import { combineReducers } from 'redux';
/**
* 一个类型的reducer
* @param {Object} state 把状态当作reducer的第一参数的默认值,
* @param {Object} action (type:'foo',payLoad:obj)
*/
const changMoney = (state = _state, action) => {
let type = action.type
// 根据action(动作)的类型,修改相应state的值
switch (type) {
case 'addMoney': state.info.money += 1000; break
case 'subMoney': state.info.money -= action.payLoad; break;
default:
}
return state
}
// 另一个类型的reducer
const changeAge = (state = _state, action) => {
let type = action.type
switch (type) {
case 'addAge': state.info.age += 1; break;
case 'subAge': state.info.age -= 1; break;
default:
}
return state
}
// combineReducers连接多个reducers
const reducer = combineReducers(
{
changMoney,
changeAge
}
)
export default reducer
store.js
import reducer from './reducer'
import _state from './state'
import _actions from './actions'
import { createStore } from "redux";
// 用reducer实例化store
export const store = createStore(reducer)
// 暴露出状态 和 actions方便页面调用
export const state = _state
export const actions = _actions
store的应用:
import React, { Component } from 'react';
// import { connect } from 'react-redux';
import { store, state, actions } from './store/store'
class App extends Component {
constructor() {
super()
this.state = {
money: state.info.money,
age: state.info.age
}
// 订阅(监听/* */)store,当触发actions时,会执行回调
store.subscribe(() => {
this.setState({
money: state.info.money,
age: state.info.age
})
})
}
componentDidMount () {
// 居然没报错,不太严谨
// state.info.money = 999
}
render () {
return (
<div className="App">
<h2>工资:{this.state.money}</h2>
<h2>年龄:{this.state.age}</h2>
<button onClick={() => actions.addMoney()}>加钱</button>
<button onClick={() => actions.subMoney(100)}>扣钱</button>
<button onClick={() => actions.addAge()}>加一岁</button>
<button onClick={() => actions.subAge()}>减一岁</button>
</div>
);
}
}
export default App
注意:action是不支持异步的
要想支持需要用到中间件 ,看大神的,或者简单地在异步成功后再触发actions
效果: