redux与react-redux(原名:react相关学习)

redux与react-redux(原名:react相关学习)

一月 11, 2021

写在前面

创建时间:2020-09-07 10:56:40

// 一看就会,一问就傻(* ̄m ̄),越学越没劲,或许我是真的不喜欢编程吧

参考资料

  1. https://www.jianshu.com/p/2eb7a12223ad
  2. [https://segmentfault.com/a/1190000015367584
  3. https://www.redux.org.cn/
  4. https://react-redux.js.org/

正篇

redux简单思想

一个应用只有一个store,通过store.getState()获取state,一个state对应一个viewview通过store.dispatch()store发出Action(其中type唯一),之后会调用reducer更新store,通过设置store.subscribe()监听改变state

其实这与订阅-发布模式很像

react-redux

react-redux提供了一个connect()来将组件与store连接,同时,这个方法有两个单数

  • mapStateToProps:每次存储状态更改时调用。它接收整个存储状态,并应返回此组件需要的数据对象。

  • mapDispatchToProps:此参数可以是函数或对象。

    • If it’s a function, it will be called once on component creation. It will receive dispatch as an argument, and should return an object full of functions that use dispatch to dispatch actions.
    • If it’s an object full of action creators, each action creator will be turned into a prop function that automatically dispatches its action when called. Note: We recommend using this “object shorthand” form.

假装这里一个栗子,当然这里例子并不好,之后会修改下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// back
const mapStateToProps = (state) => {
const resData = state[namespace];
return {
resData
};
};

// to
const mapDispatchToProps = (dispatch) => {
return {
requestSendFun: (sendData) => {
const action = {
type: `${namespace}/sendpost`,//向下传的函数名
payload: sendData
};
dispatch(action);
},
};
};

@connect(mapStateToProps, mapDispatchToProps)

react-redux与Hook

好吧,这其实才是我想讲的

useSelector()

useDispatch()

未完。。。