react-redux:

index.js:

import { legacy_createStore } from "redux";
import reducer from './reducer'

const store = legacy_createStore(reducer)
export default store

reducer.js:

const initialState = {
  num: 20,
  currentSession: {}
}
const reducer = (state = initialState, action) => {
  const newState = JSON.parse(JSON.stringify(state))

  switch(action.type) {
    case 'add':
      newState.num += action.val
    case 'transSession':
      newState.currentSession = action.val
  }
  return newState
}

export default reducer

组件:

import { useSelector, useDispatch } from 'react-redux'
// 获取
  const num = useSelector(state => state.num)

  // 更新
  const dispatch = useDispatch()
  const testChangeNum = () => {
    dispatch({ type: 'add', val: 3 })
  }

src/index.js:

import { Provider } from "react-redux";
import store from '@/app/redux/index';

  

你可能感兴趣的:(react,javascript,html,react.js,redux)