---------------根模块App.js中
import {Provider} from ‘react-redux‘;
import store from ‘./store‘;
import Header from ‘./header/Header.js‘;
class App extends Component {
render (){
return (
<Provider store={store}> //Provider将store里面的数据提供给Provider包含的所有模块使用
<Header/>
</Provider>
)
}
}
---------------子模块 Header.js
import {connect} from ‘react-redux‘;
const Header=(props)=>{
return (
<div
onClick={props.handlerClick}
>计数:{props.number}</div>
)
}
const stateToProps=(state)=>{
return ({
number:state.header.number //从传过来的state里取数据赋值给props,因为中间叠了一层header,所以取数据的时候需要从header里面取number的值
})
}
const propsToDispatch=(dispatch)=>{
return {
handlerClick(){
const action={
type:‘change_num‘
}
dispatch(action); //通过dispatch传action给reducer
}
}
}
export default connect(stateToProps,propsToDispatch)(Header); // connect将数据和子模块Header连接起来
---------------根数据store
-------------根数据store:index.js
import {createStore} from ‘redux‘;
import reducer from ‘./reducer.js‘;
export default createStore(reducer);
-------------根数据store:reducer.js
import {combineReducers} from ‘redux‘;
import headerReducer from ‘../header/reducer.js‘;
export default combineReducers({ //combineReducers合并所有的子模块reducer
header:headerReducer
})
---------------子数据header里面的reducer
const defaultState={
number:1
}
export default (state=defaultState,action)=>{
if(action.type===‘change_num‘){ //根据dispatch传过来的action,对数据state进行操作
const newState=JSON.parse(JSON.stringify(state));
newState.number++;
return newState;
}
return state;
}
原文地址:https://www.cnblogs.com/laidans/p/11622230.html