我对编写演示文稿/容器组件的方式感到非常困惑/不确定。特别是当嵌套多种方式深。我想知道如何更好地分离这些问题。
以下是我的(相关)redux状态的组合(非常简化)。
{
questions: [ // Need to get fetched from redux via selector
{
id: 1,
questionAnswers: [ // Need to get fetched from redux via selector
{
id: 1,
question: 'some question',
amount: 10 // Need to get fetched from redux via selector
},
{
id: 2,
question: 'some question',
amount: 10 // Need to get fetched from redux via selector
}
]
},
{
id: 2,
questionAnswers: [ // Need to get fetched from redux via selector
{
id: 3,
question: 'some question',
amount: 10 // Need to get fetched from redux via selector
},
{
id: 4,
question: 'some question',
amount: 10 // Need to get fetched from redux via selector
}
]
},
]
}
所以目前我创建了以下组件来使用正确的数据进行渲染,这很好。
页面组件
const Page1 = () => ({
<QuestionList />
});
QuestionList(容器)
// Gets all questions from the store
const QuestionList = ({ questions }) => ({
{questions.map(question => <Question question={question} />)}
});
问题(容器)
// Gets all questionAnswers for a question from the store
const Question = ({ question, questionAnswers }) => ({
<div>
<h3>The question itself</h3>
<div>{questionAnswers.map(answer => <QuestionAnswer answer={answer} />)}</div>
</div>
});
QuestionAnswer(容器)
// Gets the amount for each QuestionAnswer from the store
const QuestionAnswer = ({ answer, amount }) => ({
<div>
<div>{answer}</div>
<div>{amount}</div>
</div>
});
当我想要使用来自商店的不同数据重用questionList
组件时,问题就出现了。我怎么能最好地解决这个问题?我应该将所有数据连接到顶级QuestionList
而不是QuestionAnswer
,并将所有子组件表示为?这感觉非常奇怪,因为它需要包含所有questions
,questionAnswers
和questionAnswer amounts
。
答案 0 :(得分:0)
是的,我认为你的想法是正确的。 QuestionList
组件不应让Page
提出问题请求,而应该请求数据,然后将其作为道具传递给QuestionList
,如<QuestionList questions={this.state.questions} />
。这样,您可以在任何地方重复使用QuestionList
,只需为其提供您关注的数据。