Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

接入redux #1

Open
jerryni opened this issue Mar 22, 2018 · 0 comments
Open

接入redux #1

jerryni opened this issue Mar 22, 2018 · 0 comments

Comments

@jerryni
Copy link
Owner

jerryni commented Mar 22, 2018

Redux核心思想

  1. Web 应用是一个状态机,视图与状态是一一对应的。
  2. 所有的状态,保存在一个对象里面。

流程分析简介

  1. 首先,用户发出action;store.dispatch(action)
  2. 然后store自动调用Reducer,并传入2个参数:当前state和action,reducer将返回新的state,let nextState = todoApp(previousState, action);
  3. state一旦变化就会调用之前设置的监听函数store.subscribe(listener);
  4. listener可以获取到状态,然后触发react的view渲染类似function listerner() { let newState = store.getState(); component.setState(newState); }

项目分析

connect作用

第一个参数:mapStateToProps,把store上的数据作为props传递给组件,类似计算属性
第二个参数:mapDispatchToProps,将 action 作为 props 传递给组件,提供一个dispatch功能

获取products的流程:

给FilterableProductTable组件props上设置一个getProduct的方法,这个方法主要用来获取product
在componentDidMount的时候调用

生成这个getProduct的方法就是通过mapDispatchToProps的回调参数,dispatch一个相应的action,然后actions里获取到products数据,接着把当前state和新的数据扔给reducer,reducer就会处理state和新的值并更新到state中,state中的products得到了更新。

mapStateToProps监控到state发生变化,就同时更新了之前绑定到组件props上的products属性

注意点

  • api请求应该写在action里,永远不要写在reducer里,reducers应该都是纯函数, here
  • api正确的方式就是,比如登录动作,先dispatch一个login的action,成功之后再dispatch一个loginSuccess的action

参考文档

http://redux.js.org/
reduxjs/redux#291
http://taobaofed.org/blog/2016/08/18/react-redux-connect/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant