先看一下使用 redux 的元件小範例:
import {createStore} from 'redux'
import {reducer} from './redux-reducer'
const store = createStore(reducer)
export {store}
const initialState = {count: 0}
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1,
}
case 'DECREMENT':
return {
count: state.count - 1,
}
default:
return state
}
}
export {reducer}
import React from 'react'
import {useSelector, useDispatch} from 'react-redux'
function Counter() {
const count = useSelector(state => state.count)
const dispatch = useDispatch()
const increment = () => dispatch({type: 'INCREMENT'})
const decrement = () => dispatch({type: 'DECREMENT'})
return (
<div>
<h2>Counter</h2>
<div>
<button onClick={decrement}>-</button>
<span aria-label="count">{count}</span>
<button onClick={increment}>+</button>
</div>
</div>
)
}
export {Counter}
P.S. 嗚嗚,先發文再補完