1.定义action
必须有type属性, action用来表明将要更新数据
const sendAction = () => {
return {
type : 'send-type ',
value: '我是一个被传递的value'
}
}
module.exports = {
sendAction
}
2.定义reducer
通过判断action中type属性来判断对数据进行怎样的操作
const initState = {
value: '我是默认的value'
}
const reducer = (state = initState, action) => {
switch (action.type) {
case 'send-type':
return Object.assign({}, state, action)
default:
return state
}
}
module.exports = {
reducer
}
3.创建store
联系action和reducer
import { createStore } from 'redux'
// 导入创建好的reducer
import { reducer } from '../reducer/reducer'
// 创建我们自己的store 当调用store.dispatch时 action就会传递到reducer里来
const store = createStore(reducer)
export default store
4.使用
import React from 'react'
import store from '../src/store/store'
import {sendAction} from '../src/action/action'
class APP extends React.Component {
handleClick= ()=> {
const action = sendAction
store.dispatch(action)
}
// 页面一触发就拿到数据 subscribe监听数据 参数是一个回调函数, getState拿到数据
componentDidMount() {
store.subscribe(()=>{
console.log(store.getState());
})
}
render() {
return (
<div>
<button onClick={this.handleClick}>发送action</button>
</div>
)
}
}
export default APP