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

标签 javascript arrays string reactjs jsx

所以我正在开发一种测验应用程序,所以 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/

相关文章:

c++ - 传递给函数的字符串是 undefined symbol

javascript - 如何获取我的页面上每个帖子的 id?

javascript - addeventlistener 不运行函数

javascript - jqplot : how to display value from an array in a highlighter

java - 如何使用数组将实例化对象用作方法的参数

c - 在给定子字符串位置的情况下,删除 C 中的子字符串

java - 遇到将字符串转换为 Int 的递归问题

javascript - 使用 AJAX 和 PHP 检查(下载)文件是否存在

javascript - 在 Javascript 中对具有特定异常的对象数组进行排序

javascript - 名为 `name` 的数组按行而不是单词打印字符。使用 for 循环