【发布时间】:2021-01-26 09:12:54
【问题描述】:
我想用useEffect()to 代替componentWillMount(),但是我发现钩子不能在类组件中使用,所以我将代码更改为Function组件,但是整个组件会出错, this.xxx 的所有代码都出现错误,我该如何编辑下面的代码以使其正常工作?请帮我。下面的代码与componentWillMount() 一起工作正常。
import React, { Component } from 'react';
import './index.less';
import { formateDate } from '../../utils/dateUtils';
import memoryUtils from '../../utils/memoryUtils';
import { reqWeather } from '../../api/index';
import { withRouter } from 'react-router-dom';
import menuList from '../../config/menuConfig';
class Header extends Component {
state = {
currentTime: formateDate(Date.now()),
dayPictureUrl: '',
weather: '',
};
getTime = () => {
setInterval(() => {
const currentTime = formateDate(Date.now());
this.setState({ currentTime });
}, 1000);
};
getWeather = async () => {
const { dayPictureUrl, weather } = await reqWeather('Auckland');
this.setState({ dayPictureUrl, weather });
};
getTitle = (props) => {
const path = this.props.location.pathname;
let title;
menuList.forEach(item => {
if (item.key === path) {
title = item.title;
} else if (item.children) {
const cItem = item.children.find(cItem => cItem.key === path);
if (cItem) {
title = cItem.title;
}
}
});
return title;
};
componentDidMount() {
this.getTime();
this.getWeather();
}
render() {
const { currentTime, dayPictureUrl, weather } = this.state;
const username = memoryUtils.user.username;
const title = this.getTitle();
return (
<div className="header">
<div className="header-top">
<span>Welcome, {username}</span>
<a href>logout</a>
</div>
<div className="header-bottom">
<div className="header-bottom-left">{title}</div>
<div className="header-bottom-right">
<span>{currentTime}</span>
<img src={dayPictureUrl} alt="weather" />
<span>{weather}</span>
</div>
</div>
</div>
);
}
}
export default withRouter(Header)
【问题讨论】:
-
具有空依赖项的
useEffect钩子useEffect(() => {...}, [])是componentDidMount的功能组件等价物。功能组件是无实例的,所以没有this。 SO 不是代码编写服务,请尝试从基于类到功能组件的转换,如果您遇到困难,我们可以帮助您解决具体问题。 -
@Keida,请查看此文档reactjs.org/docs/hooks-reference.html。你可以随便写。
标签: javascript reactjs react-router