たぶん私は概念を正しく理解していませんでした。私は通常、例で、Counter
クラス、次にmapStateToProps
and mapDispatchToProps
、そしてを使用connect
して「高階コンポーネント」を作成し、それをデフォルトとしてエクスポートします。
このCounter
コンポーネントをどのように再利用するのでしょうか。
例えば:
Counter
同じページに2つのインスタンスが必要な場合Counter
2ページで必要な場合、それは別のredux状態(元のファイルで定義した状態ではない)に関連している必要がありますAnd then it dawns on me: it seems in practice, we actually may just define Counter.js
without all those mapStateToProps
, mapDispatchToProps
, and connect
, and then we would create IceCreamCounter.js
that first import Counter
(the plain counter) and does all the mapStateToProps
, mapDispatchToProps
, and connect
to make it into one HOC and export it?
And then if the same page need another counter, then we use mapStateToProps
, mapDispatchToProps
, and connect
in, for example, DrinkCounter.js
and do the appropriate mappings to the redux store.
Likewise, if it is the "To Go Order" page, and we need a counter for the number of spoons needed, then we actually would have mapStateToProps
, mapDispatchToProps
, and connect
and create a SpoonCounter.js
:
import { connect } from 'react-redux';
import Counter from './Counter'; // the plain counter component
const mapStateToProps = ...;
const mapDispatchToProps = ...;
const SpoonCounter = connect(mapStateToProps, mapDispatchToProps)(Counter);
export default SpoonCounter;
and that's how we achieve component re-use?
なぜこれが以前にどのように行われたのか見なかったのだろうか...それは実際にいくつかの公式ドキュメントやブログで説明されていますか?
それ自体は公式のドキュメントではありませんが、かなり「公式の」ソースからのものです。コンテナコンポーネントのパターン。これは私をパターンに向かわせた投稿です。
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
ここであなたはそれに遭遇しました。「ダム」カウンターコンポーネントは、プレゼンテーションコンポーネント、視覚的側面、UIですが、react-redux
connect
HOCは「スマート」コンポーネントを返し、アプリの状態などの有形のデータをプレゼンテーションコンポーネントに接続します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加