Redux的基本使用示例
数字加减示例
1. 创建Action
const addAction = (num) => ({
type: 'addNum',
num: num?num:1,
})
const subAction = (num) => ({
type: 'subNum',
num: num?num:1,
})
2. 创建Reducer
const reducer = (state = {count: 0}, action) => {
switch (action.type) {
case 'addNum':
state.count += action.num
break;
case 'subNum':
state.count -= action.num
break;
default:
break;
}
return {...state}
}
3. 创建Store对象
const store = Redux.createStore(reducer)
4. 在React组件中使用
class App extends React.Component {
render() {
return (
<div>
<h2>Redux练习</h2>
<h3>计数数量:{store.getState().count}</h3>
<button onClick={() => store.dispatch(addAction(1))}>加1</button>
<button onClick={() => store.dispatch(subAction(1))}>减1</button>
</div>
)
}
}
5. 监听state的变化从新渲染
store.subscribe(() => {
ReactDOM.render(
<App />,
document.querySelector('#app')
)
})
总结
const addAction = (num) => ({
type: 'addNum',
num: num?num:1,
})
const subAction = (num) => ({
type: 'subNum',
num: num?num:1,
})
const reducer = (state = {count: 0}, action) => {
switch (action.type) {
case 'addNum':
state.count += action.num
break;
case 'subNum':
state.count -= action.num
break;
default:
break;
}
return {...state}
}
const store = Redux.createStore(reducer)
class App extends React.Component {
render() {
return (
<div>
<h2>Redux练习</h2>
<h3>计数数量:{store.getState().count}</h3>
<button onClick={() => store.dispatch(addAction(1))}>加1</button>
<button onClick={() => store.dispatch(subAction(1))}>减1</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.querySelector('#app')
)
store.subscribe(() => {
ReactDOM.render(
<App />,
document.querySelector('#app')
)
})