redux-获取导航标题案例(+react-intl 国际化)

一、 案例效果

ps: 根据不同的路由切换,获取导航标题

二、配置redux

  1. npm install redux react-redux @types/react-redux redux-devtools-extension redux-thunk
  2. npm install react-intl --save (国际化,可选)
  3. index.tsx 中引入
import React from 'react';
import ReactDOM from 'react-dom/client';
import { IntlProvider } from 'react-intl';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from "react-redux";
import reportWebVitals from './reportWebVitals';
import './index.css';
import Routers from './router';
import store from "./store";
import enUS from './lang/en_US';
import App from './App';

const langMap = {
  en: enUS,
};

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <IntlProvider locale="en" messages={langMap.en}>
        <BrowserRouter>
          <App>
            <Routers />
          </App>
        </BrowserRouter>

      </IntlProvider>
    </Provider>
  </React.StrictMode>
);

// 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();

三、文件准备

在这里插入图片描述

四、代码案例

1. html下的操作

src/components/header/index.tsx

import { injectIntl } from 'react-intl';
import { useSelector } from 'react-redux'
import { rootState } from '../../store'
import './header.scss';

const Header = function InitHeader(props: any) {
  const { intl } = props;
  const home = intl.formatMessage({ id: 'intl.home' });
  const { headerInfo } = useSelector((state: rootState) => state.storeData)
  return (
    <div className="header-box">
      <div className="header-info">
        <h1 className="header-title">{headerInfo.title || home}</h1>
      </div>

      <div className="header-logo">

      </div>
    </div>
  );
};

export default injectIntl(Header);
2. store文件夹下的操作

store/index.tsx

import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import reducers from "./reducer";
export type rootState = ReturnType<typeof reducers>
const store = createStore(reducers, composeWithDevTools(applyMiddleware()))
export default store

store/reducer/index.tsx

import { combineReducers } from "redux";
import storeData from "./storeData";

export default combineReducers({storeData})

store/reducer/storeData.tsx

export interface IState {
  headerInfo: {
    title: string,
  }
} 
const initState: IState = {
  headerInfo: {
    title: '',
  }
}
export enum ActionType {
  INIT,
  HEADER_INFO,
}
const storeData = (state:IState = initState, action: { type: ActionType, payload: any }) => {
  switch (action.type) {
    case ActionType.INIT:
      console.log('state', state)
      return state
    case ActionType.HEADER_INFO:
      return {...state, ...action.payload}
    default:
      return state
  }
}
export default storeData;
3. 点击改变导航标题(side侧边导航下的操作)
import React, { useState, useEffect } from 'react';
import { injectIntl } from 'react-intl';
import headerIcon from '../../assets/img/header_icon.png';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';
import { ActionType } from '../../store/reducer/storeData'
import './index.scss';

const SideBox: React.FC = (props:any) => {
  const { intl } = props;
  const cloudCommunicator = intl.formatMessage({ id: 'intl.cloud-communicator' });
  const dataBuffering = intl.formatMessage({ id: 'intl.data-buffering' });
  const mqttBroker = intl.formatMessage({ id: 'intl.mqtt-broker' });
  const dataConnectors = intl.formatMessage({ id: 'intl.data-connectors' });
  const osiPiAf = intl.formatMessage({ id: 'intl.osi-pi-af' });

  const items: MenuProps['items'] = [
    {
      label: (
        <div className='menu-item'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      ),
      key: cloudCommunicator,
    },
    {
      label: (
        <div className='menu-item'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      ),
      key: dataBuffering,
    },
    {
      label: (
        <div className='menu-item'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      ),
      key: mqttBroker,
    },
    {
      label: (
        <div className='menu-item'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      ),
      key: dataConnectors,
    },
    {
      label: (
        <div className='menu-item'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      ),
      key: osiPiAf,
    },
  ];

  const [current, setCurrent] = useState('mail');
  const navigate = useNavigate();
  const dispatch = useDispatch()

  
  const onClick: MenuProps['onClick'] = e => {
    console.log('click ', e);
    dispatch({
      type: ActionType.HEADER_INFO,
      payload: { headerInfo: { title: e.key  } }
    })

    navigate(`/${e.key.toLowerCase().replace(/\s+/g,"")}`)
    setCurrent(e.key);
  };

  useEffect(() => {
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <div className="side-box">
      <div className="logo-box">
        <div className='logo'>
          <img role="presentation" src={headerIcon} alt="" />
        </div>
      </div>
      <Menu onClick={onClick} selectedKeys={[current]} mode="inline" items={items} />;
    </div>
  );
};
export default injectIntl(SideBox);
4. router下的操作

router/index.tsx

import { Suspense, lazy } from 'react'
import { Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('../page/home/home'));
const CloudCommunicator = lazy(() => import('../page/cloudCommunicator/cloudCommunicator'));
const DataConnectors = lazy(() => import('../page/dataConnectors/dataConnectors'));

const Routers = () => {
  return <Suspense fallback={'...loading'}>
    <Routes>
      <Route path='/' element={<Home />} />
      <Route path='/cloudcommunicator' element={<CloudCommunicator />} />
      <Route path='/dataconnectors' element={<DataConnectors />} />
    </Routes>
  </Suspense>
}

export default Routers
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值