封装hooks(日期计算函数)

function doHandleMonth(month) {
  // 如果月份只有一位数(即 1 到 9),则在前面加上 '0'
  var m = month;
  if (month.toString().length == 1) {
    m = '0' + month;
  }
  return m;
}

function GetDay(day) {
  // 获取当前日期
  var today = new Date();
  
  // 计算目标日期(当前日期 + 指定天数)
  var targetDayMilliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
  today.setTime(targetDayMilliseconds);
  
  // 获取目标日期的年、月、日
  var tYear = today.getFullYear();
  var tMonth = today.getMonth() + 1; // 注意:getMonth() 返回的月份是 0 到 11,所以加 1
  var tDate = today.getDate();
  
  // 将月和日格式化成两位数
  tMonth = doHandleMonth(tMonth);
  tDate = doHandleMonth(tDate);
  
  // 返回最终的日期字符串,格式为 "YYYY-MM-DD"
  return tYear + '-' + tMonth + '-' + tDate;
}

export default GetDay;

React Hooks 是 React 16.8 的新增特性,它可以让我们在不编写类组件的情况下,使用 state 和其他 React 特性。而封装 Hooks 则是将一些常用的逻辑抽象出来,以自定义 Hooks 的形式提供给其他组件使用。封装 Hooks 可以提高代码的复用性和可维护性。 封装 Hooks 的步骤大致如下: 1. 确定封装的逻辑,将其抽象为一个自定义 Hook 函数。 2. 在 Hook 函数中使用 React Hooks API,如 useState、useEffect 等。 3. 将 Hook 函数暴露出去,供其他组件使用。 下面是一个简单的示例,封装了一个 useFetch 自定义 Hook,用于获取数据: ``` import { useState, useEffect } from 'react'; function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function fetchData() { try { const response = await fetch(url); const json = await response.json(); setData(json); } catch (error) { setError(error); } finally { setLoading(false); } } fetchData(); }, [url]); return { data, loading, error }; } export default useFetch; ``` 这个 useFetch Hook 封装了一个异步获取数据的逻辑。其他组件可以通过调用 useFetch 获取数据并进行渲染: ``` import React from 'react'; import useFetch from './useFetch'; function MyComponent() { const { data, loading, error } = useFetch('https://jsonplaceholder.typicode.com/todos/1'); if (loading) { return <div>Loading...</div>; } if (error) { return <div>Error: {error.message}</div>; } return ( <div> <h1>{data.title}</h1> <p>{data.body}</p> </div> ); } export default MyComponent; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值