首页 > 解决方案 > Reactjs:使用 axios 调用 Api

问题描述

我是 Reactjs 的新手,我正在开发具有 .NetCore 后端的应用程序。我正在为我的前端使用 reactjs。我有一个来自 .netcore 的 api 响应,它有两种类型Internal and External,即我已将 2 个 api 调用合并在一起以做出一个响应。我的做法如下。

.NetCore 代码

在此处输入图像描述

我得到的回应如下

[
    {
        "id": 0,
        "title": "TestProductAzure",
        "description": "<p>While working with the EF Core Code-First approach, we create the classes for our domain entities first. Later, we’ll create the database from our code by using migrations. This is the opposite of the Database-First approach where we design our database first and then create the classes which match our database design.In the EF Core Code-First approach, we have full control over the code and the database is just a store without any logic. This approach is helpful in situations where we are starting with the development of a new project and we don’t have a clear picture of how our database should look like yet.We don’t have to worry about creating and updating the database. We can just make the changes in our code and then sync everything easily with the database. The important thing to note is that the manual changes that we make to the database could be lost during migration. So we should make changes to the code only.</p>",
        "owner": "Seeded Company",
        "link": null,
        "url": "http://localhost:54729/api/product/1",
        "type": "Internal",
        "rank": 0
    },
    {
        "id": 0,
        "title": "TestProductForAzure",
        "description": null,
        "owner": "Seeded Company",
        "link": null,
        "url": "http://localhost:54729/api/product/3",
        "type": "Internal",
        "rank": 0
    },
    {
        "id": 0,
        "title": "example Home Page",
        "description": null,
        "owner": null,
        "link": "/search/product?url=http://www.example.com/glossary.shtml",
        "url": "http://www.example.com/glossary.shtml",
        "type": "External",
        "rank": 0
    }
]

如上面的响应,您可以看到有不同类型的结果,即Internal and External. 要获得更清晰的图片,您可以看到如下反应的前端。

在此处输入图像描述

现在我真正想要的反应有点棘手,直到现在我在互联网上找不到任何东西。对于我来说Internal type products,我有另一个 api,例如响应特定产品的信息。

如果我们用邮递员找到第一个结果,即http://localhost:54729/api/product/1我们得到

{
    "error": false,
    "message": "Product Details",
    "data": {
        "id": 1,
        "name": "TestProductAzure",
        "heading": "Very Very Nice",
        "description": "<p>While working with the EF Core Code-First approach, we create the classes for our domain entities first. Later, we’ll create the database from our code by using migrations. This is the opposite of the Database-First approach where we design our database first and then create the classes which match our database design.In the EF Core Code-First approach, we have full control over the code and the database is just a store without any logic. This approach is helpful in situations where we are starting with the development of a new project and we don’t have a clear picture of how our database should look like yet.We don’t have to worry about creating and updating the database. We can just make the changes in our code and then sync everything easily with the database. The important thing to note is that the manual changes that we make to the database could be lost during migration. So we should make changes to the code only.</p>",
        "keywords": "Good, bad, best, abc edited",
        "posted": true,
        "category": {
            "id": 1,
            "name": "RX Product e aaa",
            "description": "Abcde gfd"
        },
        "addedDate": "0001-01-01T00:00:00",
        "modifiedDate": "2019-06-24T15:36:00.3673344",
        "addedBy": null,
        "modifiedBy": {
            "id": "ca8a4731-9717-48d5-b938-1bcad369b345",
            "userName": "ArsTestAdmin",
            "email": "abcadmin@gmail.com"
        },
        "roles": []
    }
}

我想根据特定产品的类型调用该 API。如果是External它可以直接重定向到url点击时,否则Internal它应该调用api获取信息并将其放在另一个反应页面中。我也开发了我的Internal Product Detail也。你可以看到下面的代码。

搜索结果的代码(我到目前为止所尝试的)

import React from "react";
import Rating from "./rating";
import "./test.css";
import { fetchArticle } from "../../../_actions/article.action";
import ProductDetails from "../product-details/ProductDetails";
import Axios from "axios";
import { userService } from "../../../_services";

import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect
} from "react-router-dom";
export default function SingleSearchResult(props) {
  let result = props.result;

  return (
    <div className="row">
      <div className="s130">
        {/* <div class="col-lg-8 col-xs-8 col-sm-12 col-md-7"> */}

        <div className="col-lg">
          <div className="container">
            <h3 className="search-result-heading">
              <a
                id="click"

                target="_blank"
                // onClick={handleClick(props)}
                href={
                  result.type == "Internal"
                    ? handleClick(props.result)
                    : result.url
                }
              >

                {result.title}
              </a>{" "}
            </h3>

            {result.type == "Article" ? <p>by {result.author}</p> : ""}
            <Rating rating={result.rating} />
          </div>

          <a
            href={result.url}
            target="_blank"

          >
            {" "}
            <cite class="iUh30">{result.url}</cite>
            <br />{" "}
          </a>

          <br />
        </div>
      </div>
    </div>
  );
}

function handleClick(props) {
  if (props.type == "Internal") {
    console.log(props.url);
  } else {
    return <Redirect to={props.url}></Redirect>;
  }
}

单击内部产品后的产品详细信息代码

import React from "react";
import { connect } from "react-redux";
import ProductTabs from "./ProductTabs";
import Rating from "./Rating";
import SearchBar from "../search/search-bar";

function ProductDetails(props) {
  const product = props.product;

  console.log("Received product", product);
  return (
    <React.Fragment>
      <div className="row">
        <div className="col-sm-12">
          <SearchBar />
        </div>
        <div className="col-sm-1" />
        <div className="col-sm-8">
          <div
            className="col-sm-12 col-md-12 col-lg-12"
            style={{ paddingBottom: "50px" }}
          >
            <div className="product-content product-wrap clearfix product-deatil">
              <div className="row">
                <div className="col-md-5 col-sm-12 col-xs-12 ">
                  <div className="product-image">
                    <div id="myCarousel-2" className="carousel">
                      <div className="carousel-inner">
                        <div className="item active">
                          {" "}
                          <img src={product.image} alt="" />{" "}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="col-md-7 col-sm-12 col-xs-12">
                  <h2 className="name">
                    {" "}
                    {product.title}{" "}
                    <small>
                      Product by <a>{product.company}</a>
                    </small>{" "}
                    <Rating rating={product.rating}></Rating>
                    <br />
                    <span className="fa fa-1x">
                      <h3>
                        {product.totalReviews} customer review
                        {product.totalReviews > 1 ? "s" : ""}
                      </h3>
                    </span>
                  </h2>

                  <hr />

                  <div className="certified">
                    <ul>
                      <li>Delivery time {product.deliveryTime}</li>
                      <li>Certified Quality Assured</li>
                    </ul>
                  </div>

                  <hr />

                  <div>
                    <p>{product.description}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <ProductTabs></ProductTabs>
        </div>

        <div className="col-sm-3">
          <div className="card">
            {" "}
            <img
              src="/assets/images/abbott.png"
              alt="John"
              style={{ width: "100%" }}
            />
            <h1>{product.contact.name}</h1>
            <p className="cardTitle">{product.contact.title}</p>
            <p>{product.contact.organization}</p>
            <div style={{ margin: "24px 0" }}>
              <a href={product.contact.social.dribble}>
                <i className="fa fa-dribbble" />
              </a>
              <a href={product.contact.social.twitter}>
                <i className="fa fa-twitter" />
              </a>
              <a href={product.contact.social.linkedin}>
                <i className="fa fa-linkedin" />
              </a>
              <a href={product.contact.social.facebook}>
                <i className="fa fa-facebook" />
              </a>
            </div>
            <p>
              <button
                className="cardButton"
                data-toggle="modal"
                data-target="#myModal"
              >
                Contact
              </button>
            </p>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

const mapStateToProps = state => ({
  product: state.product.product
});

export default connect(mapStateToProps)(ProductDetails);

产品详情页面如下所示 在此处输入图像描述

标签: reactjs

解决方案


推荐阅读