【问题标题】:Console log returns 3 values when only one object in state当只有一个对象处于状态时,控制台日志返回 3 个值
【发布时间】:2019-06-12 20:35:41
【问题描述】:

我正在尝试有条件地导入一个我在下面称为const techSheet 的pdf 文件,但由于某种原因,当我console.log(wine.Code) 它返回3 件事:未定义、正确结果、正确结果。

(console.log 的结果):

onewine.js:64 Code: undefined
onewine.js:64 Code: FGA-CHA17
onewine.js:64 Code: FGA-CHA17

状态中的一切看起来都很好,this.state.wine 中只有一个对象,所以我不知道为什么,#1 它返回 3 个值 #2 为什么第一个是未定义的。

import React, { Component } from "react";
import API from "../utils/API";
import { Grid} from "semantic-ui-react";
import { Link } from "react-router-dom";


class OneWine extends Component {
  state = {
    wine: {}
  };

 componentDidMount() {

    API.getWine(this.props.match.params.id)
      .then(res => this.setState({ wine: res.data }))
      .catch(err => console.log(err));
  }

render() {
    const { wine } = this.state;
    const techSheet = require(`../TechSheets/Tech_${wine.Code}.pdf`);
    console.log("Code:", wine.Code)


    return (

     <a href = {techSheet} target = "_blank" rel="noopener noreferrer">
          <Button basic color="brown" target="_blank" rel="noopener noreferrer"> Tech Sheet
          </Button>
     </a>

    );
  }
}

export default OneWine;

我没有任何其他的 console.logs 或任何东西。为什么这对于第一个来说是未定义的?

【问题讨论】:

    标签: javascript reactjs pdf import


    【解决方案1】:

    通常在此类情况下,日志语句会被多次调用。 在您的情况下,这将得到支持,因为 Render() 实际上在 ComponentDidMount() 之前被调用(请参阅:http://busypeoples.github.io/post/react-component-lifecycle/)。

    Render 在 ComponentDidMount(和其他状态更新)之后被调用两次,在 ComponentDidMount 调用之后得到正确的解决方案。

    【讨论】:

      【解决方案2】:

      这与react如何调用render方法有关。

      render 方法在 componentDidMount 之前运行。

      参考这个答案: React render() is being called before componentDidMount()

      【讨论】:

        【解决方案3】:

        因为 render 在 componentDidMount() 1 次之前被调用,此时 state 仍然是{wine: {}}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-12
          • 1970-01-01
          • 1970-01-01
          • 2016-02-17
          • 2018-05-17
          • 2019-07-18
          • 1970-01-01
          • 2019-10-06
          相关资源
          最近更新 更多