javascript - 密钥未定义 - 我无法删除
问题描述
我想在回答后删除问题。我的密钥未定义。错误:删除 http://api/Remove/undefined 400(错误请求)
state={
qBank:[{id=1,question:'dd',answers:['a','b','c','d'],correct:'a'}]
}
使成为:
this.state.qBank.map(
({ question, answers, correct, id }) => (
<QuestionBox key={id} question={question} options={answers} selected={answer => this.computeAnswer(answer, correct)} />
)
)}
import React, { useState } from 'react';
const QuestionBox = ({ question, options, selected, key }) => {
const [answer, setAnswer] = useState(options);
const [alreadyAnswered, setAlreadyAnswered] = useState(false);
return (
<div className="questionBox">
<div className="question">{question}</div>
{(answer || []).map((text, index) => (
<button disabled={alreadyAnswered} key={index} className="answerBtn" onClick={() => {
if (!alreadyAnswered) {
setAnswer([text]);
selected(text);
setAlreadyAnswered(true);
fetch("http:/api/Remove/" + key, {
method: 'DELETE',
headers: {
"Content-Type": "application/json",
"Authorization": `bearer ${sessionStorage.getItem("access_token")}`
},
}).then(() => {
}).catch(err => {
console.error(err)
})
}
}}>{text}</button>
))}
</div>
)
}
export default QuestionBox;
解决方案
key
in map 在 React 中有不同的用途。它用于渲染优化。
您不能将密钥作为道具传递。
利用
<QuestionBox key={id} id={id} question={question} options={answers} selected={answer => this.computeAnswer(answer, correct)} />
const QuestionBox = ({ question, options, selected, id }) => {
..code
}
推荐阅读
- javascript - 您如何使用 javascript 获取这些类中的内部文本?
- angular - Angular 2 - ControlValueAccessor - (ngModelChange) 未触发
- angular - NgFor 中的 ReactiveForm
- awk - awk 的奇怪行为
- oracle-apex - 基于多个表的可更新交互式网格
- regex - SSI:使用正则表达式解析变量
- ssis - 使用 SSIS 2008 R2 检索两个星号之间的字符串中的值
- java - 从 json 文件中获取动态键和值
- c# - LINQ 查询。此上下文仅支持原始类型或枚举类型
- java - 在 Windows 上安装 liquibase 并出现 java 错误