markdown React + redux基础知识

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown React + redux基础知识相关的知识,希望对你有一定的参考价值。

# React+Redux action + reducer + usage
## Actions
`actions/index.js`
```javascript 
export function actionFunction() {
  /*do somethings with data*/
  return {
    type: 'SAMPLE_ACTION' /*action type name, best from constants folder*/
    payload: data /*your data*/
  }
}
```

## Reducers
`reducers/reducer_name.js`
```javascript
export default function(state = /*initial state*/ null, action) {
  switch(action.type) {
  /* use action names from costants */
    case 'SAMPLE_ACTION': {
      /* always return piece of app redux state */
      /* never modify app state or any of its pieces */
      return action.payload
    }
  }
}
```
Always use combineReducers from redux in `reducers/index.js`
```javascript
const rootReducer = combineReducers({
  reducer_name: ReducerName
});

export default rootReducer;
```
## Usage
In your main js file `/index.js` import your combined reducers and use createStore method from redux
```jsx
const createStoreWithMiddleware = applyMiddleware()(createStore)
/*...*/
<Provider store={createStoreWithMiddleware(reducers)}>
  <App />
</Provider>
```
In your container, where you want to use that action  use functions: `mapStateToProps` and `mapDispatchToProps` and 
```jsx
/* you can use React.Component class as base or do functional component */
const ContainerName = (props) => {
  return (
    /* 
      use some jsx magic here, eg. 
      <img src={props.photo.image.source} onClick={() => props.doMagic()}/>
    */
  )
}

function mapStateToProps(state) {
    return { photo: state.photo }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ doMagic: doMagic }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(ContainerName)
```

以上是关于markdown React + redux基础知识的主要内容,如果未能解决你的问题,请参考以下文章

markdown React-Redux动手指南

markdown react-redux.d.md

学习react基础知识

electron+react-redux-saga基础项目配置

Redux 基础教程以及结合 React 使用方式

react基础---react全家桶03