1、React Component
明确你要哪个组件使用 store 中的数据
2、React Component -> Action Creators
- 在组件中构造
action
- type —— action的类型,用来判断是哪个事件要改变store
- value —— 要修改成什么值
- 使用
dispatch(action)
发送给store - 例:当我改变input中的值,会触发inputChange函数,inputChange会定义action并发送给store
import React, {Component, Fragment} from 'react'
import store from './store/index'
class Test extends Component {
constructor(props){
super(props)
this.state = store.getState()
this.inputChange = this.inputChange.bind(this)
}
render(){
return (
<input
onChange={this.inputChange}
/>
)
}
inputChange(e){
const action = {
type: 'input_change',
value: e.target.value
}
store.dispatch(action)
}
}
export default Test
3、store 会自动把 action 发给 reducers
- src/store/index.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(
reducer
//window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() // 使用Redux tools时要去掉注释
)
export default store
4、reducers -> store
- 判断 action 的
type
值是不是对应的事件 - 如果是,则把 state
深拷贝
一份出来 ——newState
- 用
action.value
改变 newState 中对应的值 - 把
newState
返回(return
)出去 - 注意:参数 state 可读,不可写,所以要深拷贝一发
- src/store/reducer.js
const defalutStore = {
inputValue: ''
}
export default (state = defalutStore, action) => {
if(action.type === 'input_change'){
const newState = JSON.parse(JSON.stringify(state)) // 简单的深拷贝
newState.inputValue = action.value
return newState
}
return state
}
5、store -> React Component
- 在组件中用
store.subscribe( [函数] )
来实时监听store的变化 - 在函数中使用
store.getState()
获取store最新的值,用this.setState()
改变组件中的state - 例:把store最新的值赋给state,然后把input的value赋值this.state.inputValue,来实时渲染页面
import React, {Component, Fragment} from 'react'
import store from './store/index'
class Test extends Component {
constructor(props){
super(props)
this.state = store.getState()
this.inputChange = this.inputChange.bind(this)
this.storeChange = this.storeChange.bind(this)
store.subscribe(this.storeChange) //实时监听
}
render(){
return (
<input
onChange={this.inputChange}
value={this.state.inputValue}
/>
)
}
inputChange(e){
const action = {
type: 'input_change',
value: e.target.value
}
store.dispatch(action)
}
storeChange(){
this.setState(store.getState()) // 把最新的store的值赋给state
}
}
export default Test