redux上⼿用⼀个累加器器举例例
- 需要⼀个store来存储数据
- store⾥的reducer初始化state并定义state修改规则
- 通过dispatch一个action来提交对数据的修改
- action提交到reducer函数里,根据传⼊的action的type,返回新的state
创建store,src/store/ReduxStore.js
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + 1
case 'MINUS':
return state - 1
default:
return state
} }
const store = createStore(counterReducer)
export default store
创建ReduxPage
import React, { Component } from "react";
import store from "../store/ReduxStore";
export default class ReduxPage extends Component {
componentDidMount() {
store.subscribe(() => {
console.log("subscribe");
this.forceUpdate();
//this.setState({});
}); }
add = () => {
store.dispatch({ type: "ADD" });
};
minus = () => {
store.dispatch({ type: "MINUS" });
};
render() {
console.log("store", store);
return (
<div>
<h3>ReduxPage</h3>
<p>{store.getState()}</p>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>
</div>
); }
}
如果点击按钮不能更新,因为没有订阅(subscribe)状态变更 还可以在src/index.js的render里订阅状态变更
import store from './store/ReduxStore'
const render = ()=>{
ReactDom.render(
<App/>,
document.querySelector('#root')
)
} render()
store.subscribe(render)
检查点
- createStore 创建store
- reducer 初始化、修改状态函数 3. getState 获取状态值
- dispatch 提交更新
- subscribe 变更订阅
使用react-redux react-redux提供了了两个api
- Provider 为后代组件提供store
- connect 为组件提供数据和变更方法
全局提供store,index.js
import React from 'react'
import ReactDom from 'react-dom'
import App from './App'
import store from './store/'
import { Provider } from 'react-redux'
ReactDom.render(
<Provider store={store}>
<App/>
</Provider>,
document.querySelector('#root')
)
获取状态数据,ReactReduxPage.js
import React, { Component } from "react";
import { connect } from "react-redux";
class ReactReduxPage extends Component {
render() {
const { num, add, minus } = this.props;
return (
<div>
<h1>ReactReduxPage</h1>
<p>{num}</p>
<button onClick={add}>add</button>
<button onClick={minus}>minus</button>
</div>
); }
}
const mapStateToProps = state => {
return {
num: state,
};
};
const mapDispatchToProps = {
add: () => {
return { type: "add" };
},
minus: () => {
return { type: "minus" };
}
};
export default connect(
mapStateToProps, //状态映射 mapStateToProps
mapDispatchToProps, //派发事件映射 )(ReactReduxPage);
connect中的参数:state映射和事件映射
网友评论