在 React 中构建调查并根据以前的答案向问题(接下来呈现的问题)添加约束,但尝试实现这些约束让我陷入了错误。
当我运行程序时,它在 QuestionComponent 中给我一个错误,试图呈现 {question} - 'objects are not valid as a React child'
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,然后将当前问题传递给您的问题组件。
关于javascript - 在 React 中构建调查并尝试对呈现的问题实现约束时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58230557/