首页 > 解决方案 > 密钥未定义 - 我无法删除

问题描述

我想在回答后删除问题。我的密钥未定义。错误:删除 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;

标签: javascriptreactjs

解决方案


keyin map 在 React 中有不同的用途。它用于渲染优化。

不能将密钥作为道具传递。

利用

<QuestionBox key={id} id={id} question={question} options={answers} selected={answer => this.computeAnswer(answer, correct)} />

    const QuestionBox = ({ question, options, selected, id }) => {
..code
}

推荐阅读