@hanyk/usestore
v1.0.2
Published
useStore
Downloads
1
Readme
安装
npm install @hanyk/usestore or
yarn add @hanyk/usestore
用法
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from '@hanyk/usestore'
export const initState = {
favourites: [],
episodes: []
}
interface State {
favourites: any[]
episodes: any[]
}
interface Action {
type: string
payload: any
}
export function reducer(state = initState, action: Action) {
switch (action.type) {
case 'FETCH_DATA':
return { ...state, episodes: action.payload }
case 'ADD_DATA':
return { ...state, episodes: [...state.episodes, action.payload] }
case 'ADD_FAV':
return {
...state,
favourites: [...state.favourites, action.payload]
}
case 'REMOVE_FAV':
return {
...state,
favourites: action.payload
}
default:
return state
}
}
const test = (id: number) => (dispatch: any) => Promise.resolve(id).then(res => dispatch({ type: 'FETCH_DATA', payload: [id] }))
const App: React.FC = () => {
const [state, dispatch] = useStore<{ episodes: [] }>()
console.log(state)
return (
<>
<button onClick={() => dispatch(test(123))}>更新</button>
<br />
{state.episodes}
<br />
<button
onClick={() =>
dispatch({
type: 'ADD_DATA',
payload: [Date.now()]
})
}
>
添加
</button>
</>
)
}
ReactDOM.render(
<Provider initState={initState} reducer={reducer}>
<App />
</Provider>,
document.getElementById('root')
)