函数组件中react-redux基本使用

安装:yarn add redux react-redux

1、定义store文件  store.js

import { createStore } from 'redux';
import reducer from './reducer';
const configureStore = () => createStore(reducer)
export default configureStore;

2、定义reducer文件  reducer.js

const initialState = {
    menuName: '首页',
    current: '123123数据'
}

// eslint-disable-next-line import/no-anonymous-default-export
export default (state = initialState, action) => {
    console.log('action', action) // 使用dispatch调用action中的方法会触发更新state 获取到action之后根据type的不同来更改不同的值    类似于action:{type: "SWITCH_MEUN", menuName: "订单管理"}
    switch (action.type) {
        case 'SWITCH_MEUN':
            return {
                ...state, // 保存上一个状态值的写法
                menuName: action.menuName
            }
        case 'SWITCH_CURRENT':
            return {
                ...state, // 保存上一个状态值的写法
                current: action.current
            }
        default:
            return { ...state }

    }
}

3、使用Provider包裹   index.js (入口文件)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import configureStore from './store/index'
const store = configureStore()

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
     <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

4、实际使用

使用useDispatch调用action修改数据

使用useSelector获取数据

import React from 'react'
import {useDispatch, useSelector} from 'react-redux'
export default function Header() {
    const dispatch = useDispatch()
    const current = useSelector((state) => {
        return state.current
    })
    const changeCurrent = ()=> {
        dispatch({
            type: 'SWITCH_CURRENT',
            current: '修改后的current'
        })
    }
    return (
        <div>
            子组件
            <h3>{current}</h3>
            <button onClick={changeCurrent}>修改current</button>
        </div>
    )
}

 

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...