前言
React 使用的是单向数据流,为了实现数据流在不同组件中实现共享,我为项目引入了 Redux 进行全局的数据状态管理。
安装依赖
首先需要安装 redux 核心依赖:
yarn add @reduxjs/toolkit
定义活动
我们在 src/Utils
下创建新的文件夹 Store
,在其中新建文件 actions.js
。
/**
* action 类型
*/
export const UPDATE_AVAILABLE_VIDEO_DEVICES = 'UPDATE_AVAILABLE_VIDEO_DEVICES'
export const UPDATE_AVAILABLE_AUDIO_DEVICES = 'UPDATE_AVAILABLE_AUDIO_DEVICES'
export const EXCHANGE_VIDEO_DEVICE = 'EXCHANGE_VIDEO_DEVICE'
export const EXCHANGE_AUDIO_DEVICE = 'EXCHANGE_AUDIO_DEVICE'
/**
* 其他常量
*/
export const DEVICE_TYPE = {
VIDEO_DEVICE: 'video',
AUDIO_DEVICE: 'audio'
}
/**
* action 活动
*/
export function updateAvailableDevices(deviceType, devices) {
switch (deviceType) {
case DEVICE_TYPE.VIDEO_DEVICE:
return { type: UPDATE_AVAILABLE_VIDEO_DEVICES, devices }
case DEVICE_TYPE.AUDIO_DEVICE:
return { type: UPDATE_AVAILABLE_AUDIO_DEVICES, devices }
default:
return null
}
}
export function exchangeMediaDevice(deviceType, deviceInfo) {
switch (deviceType) {
case DEVICE_TYPE.VIDEO_DEVICE:
return { type: EXCHANGE_VIDEO_DEVICE, deviceInfo }
case DEVICE_TYPE.AUDIO_DEVICE:
return { type: EXCHANGE_AUDIO_DEVICE, deviceInfo }
default:
return null
}
}
定义分发器
在 Store
文件夹下,创建 reducers.js
。
import { combineReducers } from '@reduxjs/toolkit';
import {
UPDATE_AVAILABLE_VIDEO_DEVICES,
UPDATE_AVAILABLE_AUDIO_DEVICES,
EXCHANGE_AUDIO_DEVICE,
EXCHANGE_VIDEO_DEVICE,
} from './actions'
function updateAvailableVideoDevices(state = [], action) {
switch (action.type) {
case UPDATE_AVAILABLE_VIDEO_DEVICES:
action.devices.push()
return action.devices
default:
return state
}
}
function updateAvailableAudioDevices(state = [], action) {
switch (action.type) {
case UPDATE_AVAILABLE_AUDIO_DEVICES:
return action.devices
default:
return state
}
}
function exchangeVideoDevice(state = null, action) {
switch (action.type) {
case EXCHANGE_VIDEO_DEVICE:
localStorage.setItem('usingVideoDevice', action.deviceInfo.key)
return action.deviceInfo
default:
return state
}
}
function exchangeAudioDevice(state = null, action) {
switch (action.type) {
case EXCHANGE_AUDIO_DEVICE:
localStorage.setItem('usingAudioDevice', action.deviceInfo.key)
return action.deviceInfo
default:
return state
}
}
const reducers = combineReducers({
availableVideoDevices: updateAvailableVideoDevices,
availableAudioDevices: updateAvailableAudioDevices,
usingVideoDevice: exchangeVideoDevice,
usingAudioDevice: exchangeAudioDevice
})
export default reducers;
导出 Redux
在 Store
文件夹下,创建 store.js
。
import { configureStore } from '@reduxjs/toolkit';
import reducers from './reducers';
const store = configureStore({
reducer: reducers,
});
export default store;