在 React 中构建调查并尝试对呈现问题实现约束时出现错误



在React 中构建调查并根据以前的答案向问题添加约束(接下来呈现什么问题(,但试图实现这些约束让我陷入了错误。

当我运行程序时,它在 QuestionComponent 中给了我一个错误,试图渲染 {question} - "对象作为 React 子项无效"

const questionArray = [
{
question: "how old are you?",
answers: [
"younger than 15",
"between 15 and 20",
"older than 20",
],
questionId: 1,
},
{
question: "are you a student?",
answers: ["yes", "no"],
questionId: 2,
condition: ( answers ) => answers[1] !== 'Yes'
},
{
question: "where do you live",
answers: ["QLD", "NSW", "VIC", "ACT", "NT", "TAS", "WA"],
questionId: 3,
},
];
export default questionArray;
______________________________________________________________________________
const QuestionComponent = ({ question, answer, onSelect }) => {
const { questions, answers } = question;
return (
<div>
{question}
{answers.map((text, index) => (
<button
key={index}
onClick={() => {
onSelect(text);
}}
>
{text}
</button>
))}
</div>
);
};
export default QuestionComponent;
______________________________________________________________________________
import questionArray from ''
import QuestionComponent from ''
class SurveyPage extends Component {
state = {
answers: {}
};
render() { 
const questions = questionBank.filter(q => {
if (!q.condition) {
return true;
}
return q.condition( this.state.answers );
});   
return (
<div>
{questions.map(question => (
<QuestionBox
question={question}
answer={this.state.answers[question.questionId]}
key={question.questionId}
onSelect={answer => {
const answers = {
...this.state.answers,
[question.questionId]: answer,
};
this.setState({ answers });
}}
/>
))}
</div>
)
}
}

我认为您应该将QuestionArr传递给调查组件,然后循环访问调查组件中的 QuestionArr,然后将当前问题传递给问题组件。

最新更新