嵌套表示/容器组件和可重用性

时间:2017-05-24 12:13:14

标签: reactjs react-redux

我对编写演示文稿/容器组件的方式感到非常困惑/不确定。特别是当嵌套多种方式深。我想知道如何更好地分离这些问题。

以下是我的(相关)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,并将所有子组件表示为?这感觉非常奇怪,因为它需要包含所有questionsquestionAnswersquestionAnswer amounts

1 个答案:

答案 0 :(得分:0)

是的,我认为你的想法是正确的。 QuestionList组件不应让Page提出问题请求,而应该请求数据,然后将其作为道具传递给QuestionList,如<QuestionList questions={this.state.questions} />。这样,您可以在任何地方重复使用QuestionList,只需为其提供您关注的数据。