首页 > 解决方案 > 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;


  

大家好,请帮助...我正在尝试使用简单的登录注册开发一个应用程序。我在上面发布的登录注册功能组件中有一个代码。我的整个应用程序代码都基于类(类组件)。你能帮我把上面的代码转换成基于类的吗?

标签: reactjs

解决方案


您可以通过五个步骤将函数组件转换为类:

  1. 创建一个扩展 React.Component 的同名 ES6 类。
  2. 添加一个分配初始 this.state 的类构造函数(以添加您的初始状态 name 和 role )。
  3. 使用 this.setState 更新您的状态(名称或角色)。
  4. 向它添加一个名为 render() 的空方法。
  5. 将函数组件内部的“return”主体移动到 render() 方法中。
  6. 在 render() 主体中用 this.props 替换 props。
  7. 你不能在你的类组件中使用 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/


推荐阅读