创建counter方法,state(初始值),action(触发的动作)
const counter = (state = 0, action = {}) => {
switch(action.type) {
case 'INCREMENT':
return state + 1;
default: return state;
}
}
export default counter;
引入 createStore from redux
import { createStore } from 'redux';
const store = createStore(reducer);
const render = () => {
ReactDOM.render(
<App
value={ store.getState() }
onClick={ () => store.dispatch({ type: 'INCREMENT' })}
/>, document.getElementById('root')
);
}
render();
store.subscribe(); //监听store发生变化
store.getState() // 获取state
store.dispatch // 更新state
React-redux
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
const mapStateToProps = (store) => {
return {
counter: store.counter
}
}
// 将 store 中的数据作为 props 绑定到组件上。
cosnt mapDispatchToProps = (dispatch) => {
return {
add: dispatch({ type: 'add' })
}
}
// 将 action 作为 props 绑定到组件上
网友评论