javascript - 无法从存储在 React 状态的数组中检索单个项目
问题描述
在我受到抨击之前:“我是 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 方法生成的随机密钥显示随机报价。
解决方案
没有渲染是异步的,它不等待 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> )
);
}
}
如果问题仍然存在,请告诉我,
推荐阅读
- javascript - 格子 - 无法运行 (python) 快速入门
- python - 如何在 Selenium 中通过它们的 innerText 定位元素 - Python
- angular - Angular忽略CSS变换属性
- python - 烧瓶容器异常行为
- sql - R:如何在 R 中使用“NOT IN”逻辑
- google-apps-script - 将文档中的占位符文本替换为工作表单元格中的文本块作为项目符号列表
- javascript - 导出变量时出现错误。有人可以帮我吗?
- java - 通过 WinAPI 提取光标大小 (Windows 10)
- hybris - 在集群环境中,如果 items.xml 发生变化,是否可以在一个节点中更新运行系统并清除其他节点的缓存?
- javascript - 如何仅添加一个特定页面的链接?