gpt4 book ai didi

javascript - 如何在react axios中获取内部数组的值

转载 作者:行者123 更新时间:2023-12-03 01:31:19 24 4
gpt4 key购买 nike

renderQuestions部分没有问题。它打印第一个问题。问题出在 renderChoices 部分。我需要的是打印第一个问题 4 选择(a.)1970 b.) 1971 c.)1972 d.)1973)。现在它打印 0 到 3 之间的数字。

import React from "react";
import axios from "axios";

class QuizApp extends React.Component {
constructor(props) {
super(props);
this.state = { questions: [], choices: [] };
}

componentDidMount() {
axios
.get("http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions")
.then(response => {
const allQuestions = [];
const allChoices = [];

response.data.forEach(({ question, choices }) => {
allQuestions.push(question);
allChoices.push(choices);
});
this.setState({ questions: allQuestions, choices: allChoices });
});
}

renderQuestions = () => {
let data = [];

this.state.questions.map((que, i) => {
data.push(<li key={i}>{que}</li>);
});
return data[0];
};
renderChoices = () => {
let data = [];

Object.keys(this.state.choices).map((ch, i) => {
Object.keys(this.state.choices[ch]).map((cc, ii) => {
data.push(<li key={ii}>{cc}</li>);
});
});
return data;
};
render() {
return (
<div>
{this.renderQuestions()}
{this.renderChoices()}
</div>
);
}
}

最佳答案

我不确定我是否明白为什么您想要呈现所有问题,然后呈现所有选择。我认为这只是一个测试?

考虑到数据的现有结构,更好的解决方案是将一个问题(及其解决方案)映射到一个组件。

像这样:

function Question (props) {
return (
<div className="Question">
<h4>{props.question}</h4>
<ul>
{props.choices.map((c, i) => (
<li className={c.correct && "correct"} key={i}>
{c.choice}
</li>
))}
</ul>
</div>
);
};

class QuizApp extends React.Component {
constructor(props) {
super(props);
this.state = { questions: [] };
}

componentDidMount() {
axios
.get(
"https://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions"
)
.then(response => {
this.setState({ questions: response.data });
});
}

render() {
return <div>{this.state.questions.map(q => new Question(q))}</div>;
}
}


ReactDOM.render(<QuizApp />, document.querySelector("#app"))
#app .Question li {
display: inline-block;
margin: 0.5em;
}

#app .Question .correct {
background-color: lime;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

您现在可以轻松修改此设置以一次仅显示一个问题。

关于javascript - 如何在react axios中获取内部数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com