javascript—使用usestate而不是基于类的组件中的状态在react钩子中编写代码

eyh26e7m  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(202)

我正在试着学习react中的钩子。我用基于类的组件编写了一些代码片段。我正在努力使用usestate和useffect将其转换为用hook编写的代码。
我有以下两个组件contactcard和contactcard,其中我在contactcard中提供了api,api在heroku服务器中提供。
我的名片

import ContactCard from "./ContactCard";
import axios from "axios";

class ContactCards extends Component {
  state = {
    contacts: [
      {
        thumbnail: clock,
        title: "Opening Times",
        data1: "",
        data2: "",
      },
      {
        thumbnail: telephone,
        title: "Phone",
        data1: "",
        data2: "",
      },
      {
        thumbnail: location,
        title: "Location",
        data1: "",
        data2: "",
      },
    ],
  };

  componentDidMount = () => {
    axios
      .get("https://example.herokuapp.com/api/contactinfo")
      .then((res) => {
        console.log(res.data[0]);
        let data = res.data[0];
        this.setState({
          contacts: [
            {
              thumbnail: clock,
              title: "Opening Times",
              data1: data.open_hour,
              data2: data.close_hour,
            },
            {
              thumbnail: telephone,
              title: "Phone",
              data1: data.phone_1,
              data2: data.phone_2,
            },
            {
              thumbnail: location,
              title: "Location",
              data1: data.street_name,
              data2: data.city + ", " + data.state + ", " + data.country,
            },
          ],
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  render() {
    return (
      <div className="contact-cards">
        {this.state.contacts.map((contact, index) => {
          return <ContactCard {...contact} key={index} />;
        })}
      </div>
    );
  }
}

export default ContactCards;

这里我将thumbnai和title作为静态数据,其中data1和data2是来自api的数据。
我的名片

interface IContactCardProps {
  thumbnail?: string;
  title?: string;
  data1?: string;
  data2?: string;
}

interface IContactCardState {}

class ContactCard extends Component<IContactCardProps, IContactCardState> {
  render() {
    return (
      <div className="contact-card">
        <div className="container">
          <div className="thumbnail">
            <img src={this.props.thumbnail} alt={this.props.title} />
          </div>
          <div className="title">{this.props.title}</div>
          <div className="data">{this.props.data1}</div> 
          <div className="data">{this.props.data2}</div>
        </div>
      </div>
    );
  }
}

export default ContactCard;

如何将api导入页面转换为使用usestate和useeffect的functioncal组件??

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题