You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React:创建新常量并推送值,及单独获取variant.text的实现问题

Alright, let's break down what's going wrong here and fix it step by step.

First, the error you're seeing ("不是函数" or "未定义") comes from trying to call currentUserAnswerVariants(variant.text)—this is an array, not a function, so you can't invoke it like that. That's why your code throws an error.

Your goal is to store variant.text in a separate variable/collection without adding it to currentUserAnswerVariants (since that breaks your POST request). Here's how to do it properly:

Option 1: Store selected texts in component state (for persistent collection)

If you need to track all selected variant.text values across checkbox changes, add a new state property to your component to hold these texts:

  1. Initialize the state (for class components):
constructor(props) {
  super(props);
  this.state = {
    selectedAnswerTexts: [] // This will hold our separate text values
  };
}
  1. Update your onChangeCheckbox function to sync the text collection with your checkbox selections:
onChangeCheckbox = (variant) => e => { 
  const { value } = e.target; 
  const { question: { currentUserAnswerVariants, maxAnswersQuantity }, updateQuestion, index } = this.props; 
  const answerIndex = currentUserAnswerVariants.indexOf(value);
  const textToStore = variant.text;
  const textIndex = this.state.selectedAnswerTexts.indexOf(textToStore);

  // Create a copy of the answer variants to avoid mutating props directly
  const updatedAnswerVariants = [...currentUserAnswerVariants];

  // Handle existing answer variants logic
  if (maxAnswersQuantity === 1 && answerIndex === -1) { 
    // For single-select, clear all existing answers
    updatedAnswerVariants.length = 0;
    // Clear the text collection too
    this.setState({ selectedAnswerTexts: [] });
  } else if (answerIndex > -1) { 
    // Remove the deselected value
    updatedAnswerVariants.splice(answerIndex, 1);
    // Remove the corresponding text from our collection
    this.setState(prevState => ({
      selectedAnswerTexts: prevState.selectedAnswerTexts.filter((_, idx) => idx !== textIndex)
    }));
  } 

  if (answerIndex === -1) { 
    // Add the selected value
    updatedAnswerVariants.push(value); 
    // Add the corresponding text to our separate collection
    this.setState(prevState => ({
      selectedAnswerTexts: [...prevState.selectedAnswerTexts, textToStore]
    }));
  }

  // Update the question via props with the copied array
  updateQuestion(index, { ...this.props.question, currentUserAnswerVariants: updatedAnswerVariants });
}

Option 2: Use a temporary variable (for one-time use in the function)

If you only need variant.text for immediate use in this function (like logging, passing to a helper, etc.), you can assign it directly without needing state:

onChangeCheckbox = (variant) => e => { 
  const { value } = e.target; 
  const { question: { currentUserAnswerVariants, maxAnswersQuantity }, updateQuestion, index } = this.props; 
  const answerIndex = currentUserAnswerVariants.indexOf(value);
  
  // Grab the text directly into a temporary variable
  const currentSelectedText = variant.text;

  // ... keep your existing logic for currentUserAnswerVariants ...

  // Use the text however you need here
  console.log("Selected option text:", currentSelectedText);
  // Example: pass to another helper function
  // this.processSelectedText(currentSelectedText);

  updateQuestion(index, { ...this.props.question, currentUserAnswerVariants });
}

Key Notes:

  • Arrays are not functions—use methods like push(), indexOf(), or spread syntax ([...array]) to work with them, never call them like array(item).
  • Avoid mutating props directly (like your original pop() or splice calls on currentUserAnswerVariants). Creating a copy first prevents unexpected side effects and follows React best practices.

内容的提问来源于stack exchange,提问作者Alexiostigrahauda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:09:41