替换数组中数据的值(React Js)



我有一个名为mcqData的对象,其中有一个称为selectedAnswer的数据,默认设置为null。我的目标是在每次我从回答单选按钮中选择一个值时,为selectedAnswer提供值。

下面显示的是mcqData对象

const mcqData = [
{
id: 0,
question: "What is a variable in software software programming?",
score: "Score 3 XP",
answers: [
{
id: 0,
answer: "Value that automatically vary"
},
{
id: 1,
answer: "A command to run your program"
},
{
id: 3,
answer: "Memory location to store some value"
},
{
id: 4,
answer: "None of the above"
}
],
correctAnswer: "Value that automatically vary",
selectedAnswer: null
},
{
id: 1,
question: "What is the answer to this expression, 22 % 3 is?",
score: "Score 5 XP",
answers: [
{
id: 0,
answer: "7"
},
{
id: 1,
answer: "5"
},
{
id: 3,
answer: "0"
},
{
id: 4,
answer: "1"
}
],
correctAnswer: "5",
selectedAnswer: null
},
{
id: 2,
question: "Which of the following will run without errors?",
score: "Score 5 XP",
answers: [
{
id: 0,
answer: "7"
},
{
id: 1,
answer: "5"
},
{
id: 3,
answer: "0"
},
{
id: 4,
answer: "1"
}
],
correctAnswer: "0",
selectedAnswer: null
}
];

这是我带答案的单选按钮的代码,

<div className="ml-14 space-y-2">
{mcq.answers.map(answer => (
<div key={answer.id} className="space-x-2">
<input className="mqc-radio-botton cursor-pointer" type="radio" name={'action' + mcq.id} id={answer.id.toString()} // checked={answer1==='answer1' } value={answer.answer} onChange={e=> {
mcq.selectedAnswer =
e.target.value;
}}
/>
<label htmlFor={answer.id.toString()} className="pl-2.5">
{answer.answer}
</label>
</div>
))}
</div>

我分配mcq.selectedAnswer = e.target.value;的方式只是暂时分配。我想将其设置为一种状态,该状态将永久地为selectedAnswer分配值。

我的想法是使用一个具有指定值的新状态,有人能帮助我如何分配具有值的状态吗(这是一个功能组件(

这里有一个基于JSON的示例。

对于同一台机器中的永久存储(即使用户刷新屏幕(,我使用的是本地存储。

export default function App() {
const [mcq, setMcq] = useState(mcqData);
useEffect(() => {
localStorage.setItem("myData", JSON.stringify(mcq));
}, [mcq]);
return (
<div className="ml-14 space-y-2">
{mcq.map((question, qindex) => {
return (
<div>
{question.id} : {question.question}
<div>
{question.answers.map((answer, aIndex) => (
<div key={answer.id} className="space-x-2">
<input
className="mqc-radio-botton cursor-pointer"
type="radio"
// name={'action' + mcq.id}
id={answer.id.toString()}
checked={question.selectedAnswer === answer}
// value={answer.answer}
onChange={(e) => {
let prevState = [...mcq];
prevState[qindex].selectedAnswer = answer;
setMcq(prevState);
}}
/>
<label htmlFor={answer.id.toString()} className="pl-2.5">
{answer.answer}
</label>
</div>
))}
</div>
</div>
);
})}
</div>
);
}

工作示例链接

https://codesandbox.io/s/cranky-carlos-how61?file=/src/App.js

最新更新