1、首先新建store文件夹,在里面引入redux
import { createStore } from 'redux';
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state > 0 ? state - 1 : state;
default: return state;
}
};
const store = createStore(reducer);
export default store;
2、在具体的页面中引入store
import React,{Component} from 'react'
import './login.scss'
import store from '../../store' //引入状态对象
class Login extends Component{
constructor(props) {
super(props);
this.state = {
count: store.getState() //获取状态数据
}
store.subscribe(() => { //监听状态变化更新数据
this.setState({
count:store.getState()
})
})
}
onIncrement = () => { //分发状态更新 存state
store.dispatch({
type:'INCREMENT'
})
}
onDecrement = () => { //分发状态更新 存state
store.dispatch({
type: 'DECREMENT'
})
}
render() {
return (
<div className="P-login">
{/*//取state*/}
<h1>{this.state.count}</h1>
<button onClick={this.onIncrement}>+</button>
<button onClick={this.onDecrement}>-</button>
</div>
)
}
}
export default Login
效果: