redux小结
-
store.dispatch(action对象)
-
在 dispatch 中调用 action 方法返回 action 对象
// '@/actions/index.js' /*** Action:* action本质上是一个 JS 对象;* 必须要包含 type 属性,否则会报错;* 只描述了有事情要发生,但并没有描述要如何更新 store 中 state*/ const action_one = (payload) => {reurn {type:'type1', ...payload} } module.exports = {action_one, }
-
-
reducer
中处理传过来的action
并更新store
数据-
通过
action
中 的type
来在 switch 中匹配对应的逻辑处理 ↓ -
逻辑处理完之后 return 更新最新的 store 数据 ↓
-
在
store.subscribe(()=>{})
回调中就可以通过store.getState()
取到最新的 store 数据
// '@/reducer/index/js' /*** Reducer:* 本质是一个函数* 用来响应发送过来的 action* 函数接收两个参数:初始化的 state、发送过来的 action* 必须要有 return 返回值,否则 state 得不到更新后的值* 【注意】return 的对象是更新后的 store 中 state 数据*/ const defaultState = {value: 'state初始值' } const reducer_one = (state = defaultState, action) => {switch(action.type){case 'type1':return {...state, ...action}case 'type2':return {...state, ...action}default:return state} }module.exports = {reducer_one, }
-
-
通过
createStore()
创建一个store
来关联action
和reducer
,如何关联?-
关联 action :
store.dispatch(action对象)
import { action_one } from '@/actions/index.js' store.dispatch(action_one()) // 注意:此处需要调用 action 函数,要用的是返回的带有type的对象 // action 函数调用返回action对象时,可以向action函数中传入别的数据,这样在返回action对象时将所传参数一起返回到action对象 store.dispatch(action_one({cs:'测试'}))
// 组件中展示(点击按钮前store中没有cs属性,页面展示“暂无”,点击按钮之后store中添加了cs属性,页面展示 “111”) import React from 'react' import store from '@/store/rumen' import { action_one } from '@/action/rumen' export default class Home extends React.Component {handlerClick() {// dispatchstore.dispatch(action_one({ cs: 111 }))}componentDidMount() {store.subscribe(() => {// 想要 store 中的 state 更改之后在页面进行展示,需要执行 this.setState({}) 此处不需要更改当前页面 state 传 {} 就可以this.setState({})})}render() {return (<><button onClick={this.handlerClick.bind(this)}>点击按钮</button><span>{store.getState().cs || '暂无'}</span></>)} }
-
关联 reducer:
createStore(reducer函数)
/*** Store* 通过 createStore 来构建 Store;* 通过 subscribe 注册监听(监听 store 中 state 是否变化),组件销毁时取消监听* 通过 dispatch 发送 action* 【作用】* 将 action 与 reducer 关联在一起*/ import { createStore } from 'redux' import { reducer_one } from '@/reducer/index.js' export default createStore(reducer_one) // 注意:需要将创建的store进行导出,别的文件才能用到
-