文章来源地址https://www.toymoban.com/news/detail-631304.html
index.ts:
import { legacy_createStore } from "redux";
import reducer from './reducer'
const store = legacy_createStore(reducer)
export default store
reducer.ts:
const defaultState = {
num: 10
}
let reducer = (state = defaultState, action:{ type: string, val: number }) => {
let newState = JSON.parse(JSON.stringify(state))
switch (action.type) {
case 'add1':
newState.num = newState.num + action.val;
break;
default:
break;
}
return newState
}
export default reducer
main.ts:
import React from 'react'
import ReactDOM from 'react-dom/client'
import Router from '@/router/index.tsx'
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Provider store={store}>
<Router />
</Provider>
</React.StrictMode>,
)
页面组件调用:
import { useSelector, useDispatch } from 'react-redux'
export default function Home() {
let num = useSelector(state => state.num)
const dispatch = useDispatch()
const handleAdd1 = () => {
dispatch({ type: 'add1', val: 5 })
}
return (
<>
<p>num: { num }</p>
<button onClick={handleAdd1}>+1</button>
</>
)
}
文章来源:https://www.toymoban.com/news/detail-631304.html
到了这里,关于react-redux的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!