Redux Hooks的使用

在react中, 博主更倾向于写函数组件, 但搜了下redux的相关教程都是基于类组件的, 所以记录一下redux的函数组件的使用方法, 用hooks来实现.

在开始之前, 我们需要用到的插件有 react-redux

使用如下命令进行安装即可

yarn add react-redux

1. 其中, 我们需要使用到的hooks函数有

import { useSelector, useDispatch } from 'react-redux'

2. 我们需要在index.js中将我们的store挂载上去, 并且使用 Provider 把根组件包裹起来, 把store传进去

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/store';
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>
  ,
  document.getElementById('root')
);

3.把创建好的store对象导出来, 因为全局只能存在一个store

store.js

import { createStore } from "redux"
import myReducers from './reducers'

export default createStore(myReducers)

4.创建一个reducer来给我们使用, 并且引入type配置

reducer.js

import { INCREMENT, DECREMENT, CHANGE_VALUE } from './action-type'
const defaultState = {
  myReducers: {
    value: '内容',
    number: 0
  }
}
export default function myReducers(state = defaultState, action) {
  console.log('test')
  switch (action.type) {
    case INCREMENT:
      state.myReducers.number += 1
      return { ...state }
    case DECREMENT:
      state.myReducers.number -= 1
      return { ...state }
    case CHANGE_VALUE:
      console.log('action', action)
      state.myReducers.value = action.value || '啥都没传'
      return { ...state }
    default:
      return { ...state }
  }
}

5.type配置一般单独写在一个文件内管理

action-type.js

export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const CHANGE_VALUE = 'CHANGE_VALUE'

6.然后在组件内调用dispatch来修改reducer中的值, 这里 useDispatch 来创建dispatch对象

componentB.js

import React, { useEffect } from "react";
import { useSelector, useDispatch } from 'react-redux'
import { INCREMENT } from '../redux/action-type'

const ComponentsB = (props) => {

  const dispatch = useDispatch()
  const test = () => {
    dispatch({ type: INCREMENT })
  }

  return <div>
    ComponentsB 
    <button onClick={() => test()}>add</button>
  </div>
}

export default ComponentsB

7. 然后在需要接受值的地方使用 useSelector 来生成一个state对象, 用来接收state值改变时传回的值, 并刷新view

App.js

import React from "react"
import ComponentsB from "./components/ComponentsB"
import { useSelector, useDispatch } from 'react-redux'
import ChangeValue from "./components/ChangeValue"

const App = () => {
  const number = useSelector((state) => { return state.myReducers.number })
  const value = useSelector((state) => { return state.myReducers.value })
  return <>
    <h2>number: {number}</h2>
    <h2>value: {value}</h2>
    <ComponentsB />
    <ChangeValue />
  </>
}

export default App

仓库地址: https://gitee.com/clgluke/redux-hooks

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注