【发布时间】:2019-02-07 20:35:12
【问题描述】:
在我被抨击之前:“我是 React 新手!”
.json 文件的 url 是:
我在我的应用程序中维护一个状态,该状态包含一个引号数组和其中的键值。
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 方法生成的随机密钥显示随机报价。
【问题讨论】:
标签: javascript arrays json reactjs axios