从 "class" 更改为 "React Hooks"
Changing from "class" to "React Hooks"
我的代码现在选择一个日期,这个 class 在另一个文件中使用。它以 ddd D MMMM 格式呈现日期的位置。我想将我的代码从 class 更改为 React 挂钩,但我不太确定该怎么做。这是代码:
import React, { Component } from "react";
import moment from "moment";
class DayPicker extends Component {
constructor(props) {
super(props);
this.state = { date: Date() };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: Date(),
});
}
render() {
return (
<div className={style.dayPicker}>
{moment()
.add(daysToAdd ? daysToAdd : 0, "day")
.format("ddd D MMMM")}
</div>
);
}
}
export default DayPicker;
如果有人设法将我的代码转换为 React Hooks,请向我解释这个过程,因为这将是一个很好的改变,以了解更多关于 React Hooks 的信息。
在将 类 转换为带有钩子的函数式组件时,您需要牢记以下事项。
首先:使用 useState
钩子代替状态。
第二:将生命周期方法更改为 useEffect
钩子。
第三:将类变量改为useRef
。
import React, { useState, useEffect } from "react";
import moment from "moment";
const DayPicker = ()=> {
const [date, setDate] = useState(new Date());
const timerID = useRef(null);
useEffect(() => {
timerID.current = setInterval(() => tick(), 1000);
return () => {
// This function will execute on unmount
clearInterval(timerID.current);
}
}, []) // empty array here signifies that the effect will be run once on initial mount
const tick = () => {
setDate(new Date())
}
return (
<div className={style.dayPicker}>
{moment()
.add(daysToAdd ? daysToAdd : 0, "day")
.format("ddd D MMMM")}
</div>
);
}
export default DayPicker;
要详细了解每个挂钩,请阅读 React docs。
我的代码现在选择一个日期,这个 class 在另一个文件中使用。它以 ddd D MMMM 格式呈现日期的位置。我想将我的代码从 class 更改为 React 挂钩,但我不太确定该怎么做。这是代码:
import React, { Component } from "react";
import moment from "moment";
class DayPicker extends Component {
constructor(props) {
super(props);
this.state = { date: Date() };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: Date(),
});
}
render() {
return (
<div className={style.dayPicker}>
{moment()
.add(daysToAdd ? daysToAdd : 0, "day")
.format("ddd D MMMM")}
</div>
);
}
}
export default DayPicker;
如果有人设法将我的代码转换为 React Hooks,请向我解释这个过程,因为这将是一个很好的改变,以了解更多关于 React Hooks 的信息。
在将 类 转换为带有钩子的函数式组件时,您需要牢记以下事项。
首先:使用 useState
钩子代替状态。
第二:将生命周期方法更改为 useEffect
钩子。
第三:将类变量改为useRef
。
import React, { useState, useEffect } from "react";
import moment from "moment";
const DayPicker = ()=> {
const [date, setDate] = useState(new Date());
const timerID = useRef(null);
useEffect(() => {
timerID.current = setInterval(() => tick(), 1000);
return () => {
// This function will execute on unmount
clearInterval(timerID.current);
}
}, []) // empty array here signifies that the effect will be run once on initial mount
const tick = () => {
setDate(new Date())
}
return (
<div className={style.dayPicker}>
{moment()
.add(daysToAdd ? daysToAdd : 0, "day")
.format("ddd D MMMM")}
</div>
);
}
export default DayPicker;
要详细了解每个挂钩,请阅读 React docs。