首页 > 解决方案 > 无法从存储在 React 状态的数组中检索单个项目

问题描述

在我受到抨击之前:“我是 React 新手!”

.json 文件的 url 是:

获取报价的 JSON

我在我的应用程序中维护一个状态,其中包含一组引号和其中的键值。

constructor(props){
    super(props);
    this.state = {
        quotes: [],
        key: 0
    };
    this.handleClick= this.handleClick.bind(this)
}

使用 axios 获取对 url 的请求时会更新状态。

 componentDidMount() {
    const url = 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json';

    axios.get(url).then((res) =>{
        const items = (res.data.quotes)
        this.setState({quotes: items})
        console.log(this.state)
    }).catch(err => console.log(err))
}

然后我希望每次点击按钮时只获得一个报价。为此,我渲染了一个“DivElement”,将特定的引号作为道具传递如下:

render() {
    return (
        <div>
        <button onClick={this.handleClick}>
            Click Me
        </button>
        <DivElement
        currentquote = {this.state.quotes[this.state.key].quotes}
        />
        </div>
    );
}

“DivElement”声明:

function DivElement(props){
console.log(props.currentquote)
return <p>{props.currentquote}</p>}

这是我得到的 TypeError:

TypeError: this.state.quotes[this.state.key] is undefined

我尝试过的事情:

没用使用 JSON.parse 方法设置状态。

我想做的事:根据 onClick 方法生成的随机密钥显示随机报价。

标签: javascriptarraysjsonreactjsaxios

解决方案


没有渲染是异步的,它不等待 API 回调。


你必须像这样有条件地渲染你的组件:

 render() {
    return (
      this.state.quotes.length && ( <div>
          <button onClick={this.handleClick}>
            Click Me
          </button>
          <DivElement
            currentquote={this.state.quotes[this.state.key].quotes}
          />
      </div> )
    );
  }
}

如果问题仍然存在,请告诉我,


推荐阅读