无法从以React

时间:2018-09-02 16:00:00

标签: javascript arrays json reactjs axios

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

.json文件的网址是:

JSON FOR GETTING QUOTES

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

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方法生成的随机键的随机报价。

1 个答案:

答案 0 :(得分:0)

没有渲染是异步的,它不等待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> )
    );
  }
}

请让我知道问题是否仍然存在,