首页 > 解决方案 > 反应渲染问题

问题描述

我有一个由 4 个组件组成的简单应用程序——除了一个组件外,大部分都可以正常工作。

4个组件

SearchContainer.js - 具有搜索按钮和文本框 - 处理提交根据搜索词获取数据,然后呈现项目组件。这工作正常

Item.js – 显示每个搜索词的项目列表和链接“产品详细信息”以获取特定项目的详细信息 – 工作正常

ProductDetail.js – 呈现项目的规格 – 以及指向比较项目的链接 – 工作正常 – 比较卡是一个反应路由器,设置用于呈现将获得不同商家价格的比较卡组件

CompareCard.js - 这是我遇到问题的地方 a) 获取/设置状态失败 - state.product_compare 没有被填充 - 奇怪的是,如果我将整个提取代码移动到相同的 api 正在填充数据产品细节组件。b)即使我在 comparecard 组件的渲染中有一个虚拟文本,也没有渲染任何内容——我在渲染中放置了一个 console.log,我可以看到该消息——但是它没有渲染任何内容。我还可以看到 prop 正在被更正地传递给比较卡组件,因为我 console.logedd 了它。c) 调用路由器的方式有问题吗?为什么相同的 api 在另一个组件中工作,但不是这个?为什么什么都没有渲染?

奇怪的是,如果我将整个 fetch 代码移动到产品详细信息组件,相同的 api 正在填充数据。

下面是 Product Detail 和 Comparecard 组件的实际代码

ProductDetail.js(通过 React Route 呈现 CompareCard)

import React from "react";
//import { Button} from 'reactstrap';
import { Link, Route, Router, HashRouter } from "react-router-dom";
import CompareCard from "./CompareCard";

const priceYugeAPI_KEY = "priceYugeAPI_KEY";
class ProductDetail extends React.Component {
  state = {
    product_details: []
  };
  componentDidMount() {
    console.log("In Product Detail", this.state.product_details);
    fetch(
      "https://price-api.datayuge.com/api/v1/compare/specs?" +
        `api_key=${priceYugeAPI_KEY}&id=${this.props.product_id}`
    )
      .then(response => response.json())
      // console.log(response.json())
      .then(jsonResp =>
        this.setState({ product_details: jsonResp.data.main_specs })
      );
  }

  render() {
    console.log("product_detail", this.state.product_details);

    return (
      <div>
        <table>
          <HashRouter>
            <p>
              <Link
                to={`/compare/${this.props.product_id}`}
                component={CompareCard}
              >
                {" "}
                Compare Card{" "}
              </Link>
            </p>
            <Route
              exact
              path={`/compare/${this.props.product_id}`}
              render={() => <CompareCard product_id={this.props.product_id} />}
            />
            <div>
              <th>Main Specs </th>
            </div>
          </HashRouter>

          {this.state.product_details.map((product_detail, index) => (
            <tr>
              <td>{product_detail}</td>
              <p> &nbsp;</p>
            </tr>
          ))}
        </table>
      </div>
    );
  }
}
export default ProductDetail;

Comparecard.js(问题组件)

import React from "react";
const priceYugeAPI_KEY = "priceYugeAPI_KEY";

class CompareCard extends React.Component {
  state = {
    product_compare: []
  };

  componentDidMount() {
    console.log("inside did mount");
    console.log("prop", this.props.product_id);
    fetch(
      "https://price-api.datayuge.com/api/v1/compare/detail?" +
        `api_key=${priceYugeAPI_KEY}&id=${this.props.product_id}`
    )
      .then(response => response.json())
      .then(
        jsonResp => this.setState({ product_compare: jsonResp.data.stores }),
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
    console.log("product_compare", this.state.product_compare);
  }

  render() {
    return (
      <div>
        <table>
          <th> Testbbbbbbbbbb {this.props.product_id}</th>
        </table>
      </div>
    );
  }
}

export default CompareCard;

CompareCard我需要在组件中为不同的商家渲染数据

标签: reactjsreact-router

解决方案


你确定你的状态没有更新吗?

在这里,您在 api 调用完成之前调用 console.log:

componentDidMount() {
    console.log("inside did mount");
    console.log("prop", this.props.product_id);
    fetch(
      "https://price-api.datayuge.com/api/v1/compare/detail?" +
        `api_key=${priceYugeAPI_KEY}&id=${this.props.product_id}`
    )
      .then(response => response.json())
      .then(
        jsonResp => this.setState({ product_compare: jsonResp.data.stores }),
        error => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
    // state hasn't been updated yet, fetch is async!
    console.log("product_compare", this.state.product_compare);
  }

render()您的中没有任何内容<CompareCard>指的是product_compare来自该州的内容。如果您将 console.log 移到那里,您应该会看到它正在更新。

  render() {
    console.log("product_compare", this.state.product_compare);
    return (
      <div>
      <table>
        <th>  Testbbbbbbbbbb {this.props.product_id}</th>
      </table>
      </div>

    )

推荐阅读