redux的使用步驟
1.在入口index.js文件中引入redux
2.创建一个store(createStore(reduces))
import React from 'react';
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import {counter} from './redux/reduces/index'
import App from './components/app.jsx'
const store = createStore(counter);
console.log(store,store.getState())
function render() {
ReactDOM.render(<App store={store} />,document.getElementById('root'))
}
render()
store.subscribe(() =>{
render()
})
3.在src目录下创建一个redux文件夹,redux下新建一个reducers文件夹,reducers下面创建一个action_type.js和index.js
index.js
import {INCREMENT,DECREMENT} from './action_type.js'
export const counter = (state =0,action) =>{
console.log('counter',state,action)
switch (action.type) {
case INCREMENT:
return state + action.data
case DECREMENT:
return state - action.data
default:
return state
}
}
action_type.js
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
3.src/components/app.jsx 使用 this.props.store.dispatch({type:DECREMENT,data:number}) 分发action,改变state
import React, { Component } from 'react';
import {INCREMENT,DECREMENT} from '../redux/reduces/action_type'
export default class App extends Component {
// state ={
// count:2
// }
increment = () =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
this.props.store.dispatch({type:INCREMENT,data:number})
// //2.得到原本的count状态,并计算新的count
// const count = this.state.count
// //3.更新状态
// this.setState({
// count:count +number
// })
}
decrement =() =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
this.props.store.dispatch({type:DECREMENT,data:number})
// //2.得到原本的count状态,并计算新的count
// const count = this.state.count
// //3.更新状态
// this.setState({
// count:count -number
// })
}
incrementIfOdd =() =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1;
//console.log(this.props.store)
//2.得到原本的count状态
const count = this.props.store.getState()
//判断,满足条件才更新状态
if(count % 2 ===1){ //是奇数
// //3.更新状态
// this.setState({
// count:count+number
// })
this.props.store.dispatch({type:INCREMENT,data:number})
}
}
incrementAsync =() =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
// //2.得到原本的count状态,并计算新的count
// const count = this.state.count
setTimeout(() => {
// this.setState({
// count:count + number
// })
this.props.store.dispatch({type:INCREMENT,data:number})
}, 200);
}
render(){
const count = this.props.store.getState();
// console.log(count)
return (
<div>
<p>click {count} times</p>
<div>
<select ref={val => this.selsectVal = val}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>increment if odd</button>
<button onClick={this.incrementAsync}>increment async</button>
</div>
</div>
)
}
}
