reactjs - react js中代码转换(从函数到类)的初学者
问题描述
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";
const Dashboard = ({ setAuth }) => {
const [name, setName] = useState("");
const [role, setRole] = useState("");
const getProfile = async () => {
try {
const res = await fetch("http://localhost:5000/dashboard/", {
method: "POST",
headers: { jwt_token: localStorage.token }
});
const parseData = await res.json();
console.log(parseData)
setRole(parseData.user_role);
setName(parseData.user_name);
} catch (err) {
console.error(err.message);
}
};
const logout = async e => {
e.preventDefault();
try {
localStorage.removeItem("token");
setAuth(false);
toast.success("Logout successfully");
} catch (err) {
console.error(err.message);
}
useEffect(() => {
getProfile();
}, []);
return (
<div>
<h1 className="mt-5">Dashboard</h1>
<h2>Welcome {name} as {role}</h2>
<button onClick={e => logout(e)} className="btn btn-primary">
Logout
</button>
</div>
);
};
export default Dashboard;
大家好,请帮助...我正在尝试使用简单的登录注册开发一个应用程序。我在上面发布的登录注册功能组件中有一个代码。我的整个应用程序代码都基于类(类组件)。你能帮我把上面的代码转换成基于类的吗?
解决方案
您可以通过五个步骤将函数组件转换为类:
- 创建一个扩展 React.Component 的同名 ES6 类。
- 添加一个分配初始 this.state 的类构造函数(以添加您的初始状态 name 和 role )。
- 使用 this.setState 更新您的状态(名称或角色)。
- 向它添加一个名为 render() 的空方法。
- 将函数组件内部的“return”主体移动到 render() 方法中。
- 在 render() 主体中用 this.props 替换 props。
- 你不能在你的类组件中使用 react Hooks (useEffect, useState),所以你需要使用 ComponentDidMount 或 ComponentDidUpdate ...(取决于情况),在你的情况下你需要使用 ComponentDidMount 因为你获取数据(在 ComponentDidMount 中调用 getProfile)。
您需要查看下面的参考资料以了解更多信息以及为什么需要使用 componentDidMount:
https://reactjs.org/docs/state-and-lifecycle.html#converting-a-function-to-a-class https://daveceddia.com/where-fetch-data-componentwillmount-vs-componentdidmount/
推荐阅读
- python - ruamel.yaml custom CommentedMapping 用于自定义标签
- java - 控制释放的键绑定不起作用
- javascript - 屏幕阅读器可访问的 React 图表库
- python - 查找图中顶点之间的所有路径
- maven - 未能执行目标 com.e-gineering:gitflow-helper-maven-plugin:2.2.0:enforce-versions
- asp.net - 在 Azure 上部署后设计混乱
- python - 如何优化 django 查询中的注释?
- python - 如何使用 Python 将表格转换为特定的 XML 格式?
- javascript - 链接到 javascript 的 href
- azure - 如何确保新创建的 prod azure 资源被策略锁定?