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入门之action #11

Open
sunyongjian opened this issue Dec 15, 2016 · 0 comments
Open

redux入门之action #11

sunyongjian opened this issue Dec 15, 2016 · 0 comments
Labels

Comments

@sunyongjian
Copy link
Owner

sunyongjian commented Dec 15, 2016

action

  • action相当于一个载体,它携带数据(可能是用户操作产生,或者接口数据),并且会根据事先定义好的type,传给store.dispatch(action),触发reducer方法,更新state。

    通常一个action是一个对象,类似于这样

    {
        type: 'UPDATE_TEXT',
        text: 'update'
    }
    

    需要dispatch更新的时候dispatch(action),就会传给reducer(action),reducer函数根据具体的type返回state,store会更新state。

  • actionCreator
    顾名思义,action创建函数。

    function updateText(text) {
       return {
         type: 'UPDATE_TEXT',
         text, 
       }
    }

    这样看起来更独立一些,当操作的时候我们只需要把text传给creator,就可以得到一个符合要求的action。所有相关的actionCreator都放到一个文件里,放到一个对象里actionCreators, 调用action的时候,只需要dispatch(actionCreators.updateText('abc'))。

bindActionCreators

这个函数接受两个参数, (actionCreators, dispatch)。 第一个参数是actionCreator的集合,是一个对象。第二个参数dispatch由store提供。
这个函数通常是配合react-redux使用,通过connect把改造后的actions对象传给Component。这样,我们就可以在一个专门的actions.js文件里定义他们,而我们的组件内部,不需要写dispatch(action)这样的操作,组件内部感知不到redux的存在。这样的好处是降低耦合性,组件内部只是调用一个方法,而这些方法通过connect传给父组件,子组件仍旧是独立的,或者说是木偶组件。

//actions.js
function updateText(text) {
return {
  type: 'UPDATE_TEXT',
  text
}
}
function addText(text) {
return {
   type: 'ADD_TEXT',
   text
}
}
const actions = { updateText, addText  }

import { bindActionCreators, createStore } from 'redux';
const store = createStore(reducer);
const bindActions = bindActionCreators(actions, store.dispatch)
store.actions = bindActions;

ReactDOM.render(
<App  store />
)
//伪代码
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant