javascript - 作为返回数组的函数的结果,我们如何在 useState 中设置初始状态?
问题描述
我的 JSON 对象由字符串类型的正确答案和不正确答案(我想在错误答案数组中推送正确答案的数组)组成,修改后我希望这个 JSON 对象作为我们使用 React 创建的已修改状态的初始值钩子。我怎样才能做到这一点。
var css = "ma2 pa2 br-pill dim pointer grow hover w-20";
const Logic = (props) => {
const ques = props.questions;
const [count, setCount] = useState(0);
//const [ques, setQues] = useState(props.questions);
const [modified, setModified] = useState((ques) => () => {
for (var i = 0; i < ques.length; i++) {
ques[i].incorrect_answers.push(ques[i].correct_answer);
}
return ques;
});
return (
<div className="tc">
{modified.length !== 0 ? (
<div>
{modified[count].incorrect_answers.map((home) => (
<div>
<button className={css}>{home}</button>
</div>
))}
</div>
) : (
<h1>loading</h1>
)}
</div>
);
};
export default Logic;
我作为道具得到的 JSON 对象看起来像
{
> "response_code": 0,
> "results": [
> {
> "category": "Entertainment: Video Games",
> "type": "multiple",
> "difficulty": "medium",
> "question": "When was the original Star Wars: Battlefront II released?",
> "correct_answer": "October 31, 2005",
> "incorrect_answers": [
> "December 18, 2004",
> "November 21, 2006",
> "September 9, 2007"
> ]
> },
> {
> "category": "Entertainment: Japanese Anime & Manga",
> "type": "multiple",
> "difficulty": "medium",
> "question": "In Dragon Ball Z, who was the first character to go Super Saiyan 2?",
> "correct_answer": "Gohan",
> "incorrect_answers": [
> "Goku",
> "Vegeta",
> "Trunks"
> ]
> },
> {
> "category": "Science & Nature",
> "type": "multiple",
> "difficulty": "easy",
> "question": "The human heart has how many chambers?",
> "correct_answer": "4",
> "incorrect_answers": [
> "2",
> "6",
> "3"
> ]
> }
> }
解决方案
您可以使用 useEffect 挂钩来操作数据并将其存储在修改后。
const [modified, setModified] = useState([]);
useEffect(() => {
setModified(props.questions.map(data=>({...data,incorrect_answers:data.incorrect_answers.concat([data.correct_answer])})));
}, [props.questions]);
推荐阅读
- twitter-bootstrap - Twitter Bootstrap,将第三个 md-6 列集中在中型设备上
- kubernetes - Terraform dial tcp 192.xx.xx.xx:443: i/o timeout error
- sql-server - 如何配置 AKS 部署以使 ASP.NET 应用能够连接到 Azure SQL 数据库
- python - Dockerfile 中的 WORKDIR 指令在容器化 Python 应用程序时无效
- php - PayPal webhook 创建与激活
- visual-paradigm - Visual Paradigm CE - 不打开项目文件
- python-3.x - 如何使用 Python 提取特定单词周围的当前句子和周围句子?
- linux - 如何可靠地
到标准输出? - javascript - 打字稿/反应:在上下文减速器中返回的对象无效属性未显示错误
- youtube - 如何对齐嵌入的 Youtube 视频