react-redux

react-redux_第1张图片

 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(
  
    
      
    
  ,
)

页面组件调用:

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 (
    <>
      

num: { num }

) }

你可能感兴趣的:(react,react.js,javascript,前端)