如何使用redux
1.在src index.js
import React from 'react';
import ReactDOM from 'react-dom'
import App from './components/app.jsx'
import store from './redux/store'
function render() {
ReactDOM.render(<App store={store} />,document.getElementById('root'))
}
render()
store.subscribe(() =>{
render()
})
2.在src目录下新建redux文件夹
3.在redux目录下新建store.js,reducers.js,actions,action_type.js
store.js
import {createStore} from 'redux'
import {counter} from './reducers.js'
const store = createStore(counter);
console.log(store,store.getState())
export default store
reducers.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
}
}
actions.js
import {INCREMENT,DECREMENT} from './action_type'
//增加
export const increment =(number) => ({type:INCREMENT,data:number})
//减少
export const decrement =(number) => ({type:DECREMENT,data:number})
action_type.js
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
app.jsx(src >components >app.jsx)
import React, { Component } from 'react';
import * as actions from '../redux/actions'
export default class App extends Component {
increment = () =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
this.props.store.dispatch(actions.increment(number))
}
decrement =() =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
this.props.store.dispatch(actions.decrement(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){ //是奇数
this.props.store.dispatch(actions.increment(number))
}
}
incrementAsync =() =>{
//1.得到选择增加数量
const number = this.selsectVal.value*1
// //2.得到原本的count状态,并计算新的count
// const count = this.state.count
setTimeout(() => {
this.props.store.dispatch(actions.increment(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>
)
}
}
问题
1.redux与react组件的代码耦合度太高
2.代码不够简洁