15.动态获取当前时间/天气/标题
因为用的最新的React版本【18】 + React-router【6.8.1】所以获取地址栏信息需要使用useLocation,因此 改为 函数式编程如下:
/* 头部导航组件 */ import React, {useEffect, useState} from "react"; import {message} from 'antd' import {useLocation} from "react-router-dom"; import {formatDate} from '../../utils/dateUtils' import { reqWeather } from '../../api/index' import memoryUtils from "../../utils/memoryUtils"; import './index.css' import weather from './sun_weather.png' import menuList from '../../config/menuConfig' export default function Header(){ // 函数式组件 中的this 是undefined ,因为babel编译后开启了严格模式 const [weatherStr, setWeather] = useState('多云') // console.log("props =", props, "weather =", weather, "setWeather =", setWeather) const [dateStr, setDate] = useState(formatDate(Date.now()) ) const [titleStr, setTitle] = useState('' ) let current_path_obj = useLocation() // 返回一个对象 {pathname: '/role', search: '', hash: '', state: null, key: 'fmqz5mcg'} // console.log("date =", date, "setDate =", setDate) // 获取天气 async function getWeather(){ const res = await reqWeather("110100") console.log(" req weather res ==", res) if (res['code'] === 1){ const weather_str = res['data']["text"] setWeather(weather_str) }else{ message.error("获取天气信息出错!") } } // 获取当前路由路径并获取名字展示 function getTitle(){ console.log("current path ==", current_path_obj.pathname) let temp_path = '' menuList.forEach(item => { if(item.key === current_path_obj.pathname) { temp_path = item.label }else if (item.children){ const subItem = item.children.find(subItem => subItem.key === current_path_obj.pathname) if(subItem){ temp_path = subItem.label } } }) return temp_path } /* 类组件 使用 componentDidMount 第一次render() 之后执行一次 函数组件使用 useEffect --> 副作用,有两个参数 第一个参数 函数:相当于类式中的DidMount和DidUpdate,但是由后面的第二个参数来决定 第二个参数[] 不写数组监测所有数据想当于Mount和Update,写了空数组都不监测即Mount; 一般在此执行异步操作:发ajax请求/启动定时器 类似 vue的mounted */ useEffect(() => { console.log("useEffect") getWeather() let temp_path = getTitle() setTitle(temp_path) // 启动定时器 获取当前时间不断更新 let timer = setInterval(()=>{ setDate(dateStr => formatDate(Date.now())) }, 1000) // 返回值是 组件销毁前的生命周期 return () => { // 组件销毁前,销毁定时器 clearInterval(timer) } }, [titleStr]) const username = memoryUtils.user.username return ( <div className="header"> <div className="header-top"> <span>欢迎, {username}</span> <a href="#">退出</a> </div> <div className="header-bottom"> <div className="header-bottom-left">{titleStr}</div> <div className="header-bottom-right"> <span>{dateStr}</span> <img src={weather} alt="weather"/> <span>{weatherStr}</span> </div> </div> </div> ) }