【发布时间】:2020-11-20 06:08:27
【问题描述】:
在 this.state 中存储对象数组后,我尝试访问对象中的值,例如 Array[random].someValue,但它显示错误 Array[random] is undefined。但它适用于Array[random] 返回一个对象。为什么我不能访问该对象内的值...?
class Quiz extends Component {
constructor(props) {
super(props);
this.state = {
data: undefined,
q_no: 0,
rand_q: {},
opts: []
}
this.newQuestion = this.newQuestion.bind(this);
}
componentDidMount() {
if(this.state.data === undefined) {
fetch("http://restcountries.eu/rest/v2/all")
.then(data => data.json())
.then(data => this.setState({data: [data.map((val) => ({name: val.name, flag: val.flag}))]}))
.then(() => console.log(this.state.data));
}
}
newQuestion() {
const state = this.state;
const rand = Math.floor(Math.random() * 200);
this.setState({rand_q: {name: state.data[rand].name, flag: state.data[rand].flag}, opts: [state[rand-1].name, state[rand+1].name, state[rand+2].name]});
}
TypeError: state.data[rand] is undefined
newQuestion
src/Quiz.js:30
27 | newQuestion() {
28 | const state = this.state;
29 | const rand = Math.floor(Math.random() * 200);
> 30 | this.setState({rand_q: {name: state.data[rand].name, flag: state.data[rand].flag}, opts: [state[rand-1].name, state[rand+1].name, state[rand+2].name]});
| ^ 31 | }
32 |
33 | render() {
请帮忙...
【问题讨论】:
-
你的 JSX 有没有可能有类似
<button onClick={this.newQuestion()} ...的东西?因为这将在渲染期间运行该函数,而不是在单击按钮时运行,这为时过早。你需要onClick={() => this.newQuestion()}代替,如果你使用它,你也可以从构造函数中删除bind行。通常,您可能希望在this.state.data未定义时显示加载文本,使用条件渲染。 -
不..
<Form newQuestion={this.newQuestion} />.. -
好的...那么你在哪里调用这个函数呢?
-
能贴出完整的代码吗?
-
所以如果你在第 30 行设置状态之前添加一个额外的行,
console.log(this.state.data[rand])它会给你一个值而不是 undefined 吗?
标签: javascript node.js json reactjs