例子1:只有加减,判断奇数偶数加减和异步加
组件里面的调用:
const { value, onIncrement, onDecrement } = this.props
return (
<p>
Clicked: {value} times
<button onClick={onIncrement} + </button>
<button onClick={onDecrement}> - </button>
<button onClick={this.incrementIfOdd}>
Increment if odd
</button>
<button onClick={this.incrementAsync}>
Increment async
</button>
</p>
)
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>
reducers:
export default (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
因为当前store里面只有一个值,所以value==state
例子2:最简单的一个页面包括所有
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
// 组件里面通过props调用方法,拿数据
class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}
// 定义动作
const increaseAction = { type: 'increase' }
// 处理动作
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
case 'increase':
return { count: count + 1 }
default:
return state
}
}
// 唯一一个状态树
const store = createStore(counter)
// 组件状态的改变放到store里
function mapStateToProps(state) {
return {
value: state.count
}
}
// 页面调用事件
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}
// 链接组件和状态树
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
例子3:新增待办事项,点击表示事件完成。过滤显示全部、已完成、未完成。
定义动作,包括类型,id和文字内容
let nextTodoId = 0
export const addTodo = (text) => ({
type: 'ADD_TODO',
id: nextTodoId++,
text
})
// 定义动作,包括类型,是否完成
export const setVisibilityFilter = (filter) => ({
type: 'SET_VISIBILITY_FILTER',
filter
})
export const toggleTodo = (id) => ({
type: 'TOGGLE_TODO',
id
})
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}
reducer 就是一个纯函数,接收旧的 state 和 action,返回新的 state。
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO': // 新增待办事项,返回新的 state
return [
...state,
{
id: action.id,
text: action.text,
completed: false
} // 新的 state = 旧的 + 这一次动作的id和text
]
case 'TOGGLE_TODO':
return state.map(todo =>
(todo.id === action.id)
? {...todo, completed: !todo.completed}
: todo
)
default:
return state
}
}
export default todos