【问题标题】:Handling fetched objects in React components在 React 组件中处理获取的对象
【发布时间】:2021-08-04 19:13:28
【问题描述】:

我是一名 React 新手,正在 FCC 上学习,我正在努力处理获取的对象。

我正在尝试构建一个基本的“随机报价机”React 组件,该组件获取(然后从其中呈现值)一个对象。对象(在 componentDidMount 中获取)有一个键 (quotes),它是一个对象数组(每个对象都有 quote >author 键),然后我将此数组分配给本地状态 (quotesData),然后在 render 中作为常量。

本质上,组件应该在第一次 render 时显示一个随机引用,然后在每次单击 New Quote 按钮 时再次显示。因此,我(随机)将数组中的一个对象分配给 nextQuote。 在此之后,我遇到了问题。我可以console.log(quotesData)(和nextQuote)没有问题,但为什么我不能从存储在nextQuote中的对象分配值到 nextQuoteQuotenextQuoteAuthor,使用点(或括号)表示法?

这是笔的链接(完整代码也在下面):https://codepen.io/igorgetmeabrain/pen/rNmwMEM

现在,它只是不断地向我抛出对象错误并且根本不会渲染。请帮忙!

class RandomQuotes extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isFetching: false,
      quotesData: [],
      random: Math.random()
    };
    this.getNewQuote = this.getNewQuote.bind(this);
    this.fetchData = this.fetchData.bind(this);
  }
  
  fetchData() {
    this.setState({isFetching: true});
   fetch ('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json', 
{headers: {
      Accept: 'application/json'
    }})
      .then(res => res.json())
      .then((data) => 
            {
      this.setState({quotesData: data.quotes, isFetching: false});
      })
    .catch(error => {
                console.log(error);
                this.setState({isFetching: false, error: error});
            });
  }
  
  getNewQuote() {
    this.setState({
      random: Math.random()
    });
  } 

  componentDidMount() {
    this.fetchData();
  }

  render() {
    const {quotesData, isFetching, error} = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (isFetching) {
      return <div>Loading...</div>;
    } else {
      const randomIndex = Math.floor(this.state.random * quotesData.length);
      const nextQuote = quotesData[randomIndex];
      const nextQuoteQuote = nextQuote.quote;
      const nextQuoteAuthor = nextQuote.author;
      return (
      <div id="quote-box">
        <p id="text">{nextQuoteQuote}</p>
        <p id="author">{nextQuoteAuthor}</p>
        <button id="new-quote" onClick={this.getNewQuote}>
          New Quote
        </button>
      </div>
    );
  }
 }
}

ReactDOM.render(<RandomQuotes />, document.getElementById("root"));

【问题讨论】:

    标签: javascript json reactjs fetch-api


    【解决方案1】:

    最快的解决方法是更改​​状态中的isFetching: true。 发生这种情况是因为在开始时如果 isFetching: falseerror: false 它进入您定义的最后一个 } else { 部分

    const nextQuoteQuote = nextQuote.quote;
    const nextQuoteAuthor = nextQuote.author;
    

    这是未定义的,因为数据正在后台获取并且尚未获取。

    因此,基本上当您必须在 componentDidMount 方法中获取数据时,您从一开始就将加载状态设置为 true,以便组件知道它必须等待它获取并稍后显示数据。

    【讨论】:

    • 我不敢相信这已经让我发疯了好几天,而且简单的解决了它,谢谢!
    • 不客气 :) @igorgetmeabrain 如果您可以将我的答案设置为很棒的解决方案!
    猜你喜欢
    • 1970-01-01
    • 2015-02-19
    • 2022-01-01
    • 2019-02-23
    • 1970-01-01
    • 2022-11-04
    • 2021-09-11
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多