structure
-
component1
- actions.js
- reducer.js
- component1.js
-
component2
- actions.js
- reducer.js
- component.js
-
redux
- tore.js
- app.js
Component 1
action.js
export function increment(){
return {
type: "+"
}
}
export function decrement(){
return {
type: '-'
}
}
reducer.js
export default (state = 0, action) => {
switch(action.type){
case '+':
return state + 1;
case '-':
return state - 1;
default:
return state;
}
}
component.js
import React, {Component} from 'react'
import {connect} from 'react-redux'
import * as Actions from './actions'
import Component2 from '../cp2/cp2'
class Component1 extends Component{
increment = () => {
console.log(this.props)
this.props.increment();
}
render(){
return (
<div>
<h3>component-cp1-{this.props.cp1}</h3>
<input type="button" value="increment" onClick={this.increment}/>
<Component2 />
</div>
)
}
}
const mapStateToProps = (store) => {
return {
cp1: store.cp1
}
}
export default connect(mapStateToProps, Actions)(Component1)
Component 2
action.js
export function increment(){
return {
type: "+"
}
}
export function decrement(){
return {
type: '-'
}
}
reducer.js
export default (state = 0, action) => {
switch(action.type){
case '+':
return state + 1;
case '-':
return state - 1;
default:
return state;
}
}
component.js
import React, {Component} from 'react'
import {connect} from 'react-redux'
import * as Actions from './actions'
class Component2 extends Component{
render(){
return (
<div>
<h3>component-cp2-{this.props.cp2}</h3>
</div>
)
}
}
const mapStateToProps = (store) => {
return {
cp1: store.cp1,
cp2: store.cp2
}
}
export default connect(mapStateToProps, Actions)(Component2)
store.js
import {createStore} from 'redux';
import { combineReducers } from 'redux';
import cp1 from '../components/cp1/reducer'
import cp2 from '../components/cp2/reducer'
const rootReducer = combineReducers({
cp1,
cp2
});
const store = createStore(rootReducer)
export default store;
app.js
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, hashHistory} from 'react-router'
import {Provider} from 'react-redux'
import store from './redux/configStore'
import Component1 from './components/cp1/cp1'
ReactDOM.render(
<Provider store={store}>
<Component1/>
</Provider>,
document.getElementById('app')
)
Summary
- Component uses
react-redux.connet
takestate
andaction
All merged intoprops
Zhongqu -
connet
The first parameter is a method, and the first parameter of the method isstore
That is, throughredux.combineReducers
To merge and get onerootReducer
- Used in the outermost root element
react-redux.Provider
Component, its propertiesstore
It’s throughredux.createStore
It came outstore
- When passed
props
callactions
When,redux
It’s called implicitlystore.dispath
Instead of calling it manually. - stay
reducer
The value returned in themapStateToProps
Instead of calling manuallystore.getState()