gpt4 book ai didi

javascript - 在javascript,reactjs中拆分字符串

转载 作者:行者123 更新时间:2023-11-30 11:30:07 24 4
gpt4 key购买 nike

所以我正在开发一种测验应用程序,所以 this是应用程序首次启动时的初始状态,我还有 quizApplication.js 组件存储所有问题和答案,

{
question: "I am task oriented in order to achieve certain goals",
answers: [
{
type: "Brown,D,JP",
content: "Hell Ya!"
},
{
type: " ",
content: "Nah"
}
]
},

这是我设置用户答案的​​函数

setUserAnswer(answer) {
if (answer.trim()) {
const answer_array = answer.split(',');
const updatedAnswersCount = update(this.state.answersCount, {
[answer]: {$apply: (currentValue) => currentValue + 1},
});
this.setState({
answersCount: updatedAnswersCount,
answer: answer
});
}
}

我也有这样的 AnswerOption 组件

function AnswerOption(props) {
return (
<AnswerOptionLi>
<Input
checked={props.answerType === props.answer}
id={props.answerType}
value={props.answerType}
disabled={props.answer}
onChange={props.onAnswerSelected}
/>
<Label className="radioCustomLabel" htmlFor={props.answerType}>
{props.answerContent}
</Label>
</AnswerOptionLi>
);
}

所以我尝试做的是每当用户点击 HellYa!它会将“Brown”、“D”和“JP”递增 +1,但现在它给了我一个新的 answersCount 值 Brown,D,JP: null,那么我应该如何实现呢?非常感谢!

最佳答案

您已经拆分了您的类型,但还没有使用它们。

当您拆分type 时,您将得到长度为3answer_array,其中包含["Brown", "D", "JP"]

const answer_array = answer.split(',');

接下来,您将使用更新后的答案计数来更新您的状态。您正在执行以下操作

const updatedAnswersCount = update(this.state.answersCount, {
[answer]: {$apply: (currentValue) => currentValue + 1},
});

这里的answer包含"Brown,D,JP"。由于您希望通过 +1 更新每个值,因此让我们遍历拆分值并更新它。

let updatedAnswersCount = null;

answer_array.forEach((key) => {
updatedAnswersCount = update(this.state.answersCount, {
[answer]: {$apply: (currentValue) => currentValue + 1},
});
}

在这里,我假设您的类型是独一无二的。意思是 Brown/D/JP 仅针对此答案存在,而不针对其他任何内容。所以我们假设所有人都具有相同的值(value)。

关于javascript - 在javascript,reactjs中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46570887/

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