私はあなたがする必要はないと思います。
(申し訳ありませんが、私の経験では最高の解決策です)
ストアはデータの真実の源です。これは問題ありません。
React Routerを使用している場合は、それをあなたのURL状態の真実の源にします。
すべてを店舗に保管する必要はありません。 URLパラメータが唯一の講義のナメクジと選択されている章が含まれているため
:あなたのユースケースを考えると例えば
、。ストアでは、名前、スラッグ、および選択されたブール値の講義とチャプターのリストがあります。
問題は、データを複製していることです。ストア内のデータ(chapter.selected
)は、React Router状態で複製されます。 1つの解決策がそれらを同期させることになりますが、これはすぐに複雑になります。 React Routerを選択した章の真実の源にするだけではどうですか?
あなたの店の状態は、(簡体字)のようになります。
{
// Might be paginated, kept inside a "book", etc:
visibleChapterSlugs: ['intro', 'wow', 'ending'],
// A simple ID dictionary:
chaptersBySlug: {
'intro': {
slug: 'intro',
title: 'Introduction'
},
'wow': {
slug: 'wow',
title: 'All the things'
},
'ending': {
slug: 'ending',
title: 'The End!'
}
}
}
それだそれ!そこにはselected
を保管しないでください。代わりに、React Routerがそれを処理させます。あなたのルートハンドラーで、次のように書く
function ChapterList({ chapters }) {
return (
<div>
{chapters.map(chapter => <Chapter chapter={chapter} key={chapter.slug} />)}
</div>
)
}
const mapStateToProps = (state, ownProps) => {
// Use props injected by React Router:
const selectedSlugs = ownProps.params.selectedSlugs.split(';')
// Use both state and this information to generate final props:
const chapters = state.visibleChapterSlugs.map(slug => {
return Object.assign({
isSelected: selectedSlugs.indexOf(slug) > -1,
}, state.chaptersBySlug[slug])
})
return { chapters }
}
export default connect(mapStateToProps)(ChapterList)
なぜ、React RouterをURLパラメーターの真理値のソースとして使用するのではなく、ユーザーが入力した小道具を使用するのかmapStateToProps(state、ownProps)? –
urlパラメータには、講義のスラッグと選択されたチャプタだけが含まれているためです。ストアでは、名前、スラッグ、および選択されたブール値の講義とチャプターのリストがあります。例えば、 – JoKer
。 https://peterbeshai.com/react-url-query/を使用しますか? – mb21