React-hooks context上下文的使用

// 创建context.js
import { createContext } from “react”;

const Context = createContext(null);

export default Context;

// 创建initialState.js
export const initialState = {
list: [],
clearTimer: null,
packFile: ‘’,
disabledState: false
}

// 创建reducer.js
function reducer (state, action) {
switch (action.type) {
case “setList”:
return {
…state,
list: action.list
};
case “setClearTimer”:
return {
…state,
clearTimer: action.clearTimer
};
case ‘setPackFile’:
return {
…state,
packFile: action.packFile
};
case ‘setDisabledState’:
return {
…state,
disabledState: action.disabledState
}
default:
throw new Error();
}
}
export default reducer;

// 挂到顶层标签中
import React, { useState, useEffect, useReducer } from ‘react’;
import { Layout, Breadcrumb, Alert } from ‘antd’;
import breadcrumbData from ‘…/layout/breadcrumb/breadcrumbData’
import ‘./index.less’
import Routes from ‘./…/router/routes’
import Context from ‘./…/context/context’
import { initialState } from ‘./…/context/initialState’
import reducer from ‘./…/context/reducer’

const { Content, Footer } = Layout;

function Contents (props) {
const { keyValue } = props
const [secondLevel, setSecondLevel] = useState()
const [firstLevel, setFirstLevel] = useState();
const [state, dispatch] = useReducer(reducer, initialState);

// 截取 “/” 字符前后数据
const getStr = (string, str) => {
var str_before = string.split(str)[0];
var str_after = string.split(str)[1];
var obj = {
firstMenu: str_before,
scondMenu: str_after
};
return obj;
}

useEffect(() => {
// 面包屑赋值
for (let item in breadcrumbData) {
if (keyValue && keyValue === item) {
let menuData = getStr(breadcrumbData[item], ‘/’)
setSecondLevel(menuData.scondMenu)
setFirstLevel(menuData.firstMenu)
}
}
}, [keyValue])

return (





{firstLevel}
{secondLevel}




版权所有 © 2022



)
}

export default Contents

// 在组件中使用
function Bae () {
const { list, clearTimer, packFile, disabledState } = state;

// 修改数据
const stop = async () => {
let res = await replayStop();
if (res && res.res) {
dispatch({
type: ‘setPackFile’,
packFile: “”
})
setBtnChildren(true)
message.success(res.message)
setFileShow(false);
} else {
message.error(res.message)
setBtnChildren(true)
}
}
}

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