New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Reactのエンドポイントの処理を書き換えて、連番でなくても重複が無ければ表示されるようにした #70
Conversation
divのidの名前にapplication.jsxのエンドポイント側の特定の文字列が入っていればOK
@@ -5,14 +5,19 @@ import Mount from "./Mount"; | |||
const MountComponents = ( | |||
component: unknown, | |||
divName: string, | |||
numberOfComponents: number | |||
divElements: NodeListOf<HTMLDivElement> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
カーソルを当てると型が分かる場合がある
} | ||
} | ||
|
||
const divNames = Array.from(elements).map((div) => div.id); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Array.from()
を使用して、HTMLDivElement[]
を配列に変換している。そして、Array.prototype.map()
を使用して、各要素のidプロパティを文字列に変換し、divNames
へと格納している。
MountComponents(Hey, "hey", divElements); | ||
MountComponents(Hola, "hola", divElements); | ||
// holaholaをHelloでマウントしている。実験的な例。 | ||
MountComponents(Hello, "holahola", divElements); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
必要十分条件の実験。コード上のこの順番なら大丈夫。
下のコードは悪い例。
MountComponents(Hello, "holahola", divElements);
MountComponents(Hola, "hola", divElements);
この場合はholahola
と書いていても、Hola
のほうでマウントされてしまうのでバグを生む可能性がある。
補足:名前に重複があると、次のような
|
以前の状態では、必ずdivのidが
hoge1
から始まる連番になっている必要があり、Viewファイルを書くのが大変だった。しかし、このPull Requestにより、
div
のIDの文字列が被っていなければ表示されるようになったので、一つのViewファイルで複数のReactコンポーネントを簡単に表示できるようになった。具体的には、
kaminari
のようなgemを使うと、例えば1ページ目の表示数が10
だとすると、.each.with_index(1)
を使ったとしても、2ページ目のdivのidがhoge11
から始まってしまい、そのページでは1
からのスタートでは無くなってしまうため、Reactが表示されなくなってしまう恐れがあった。今回の改善により、仮に
hoge11
から始まったとしても、問題なく表示されるようになった。重複が無く、なおかつエンドポイント側で指定された文字列が入っていればOKだからである。※一点だけ注意点がある。
エンドポイントがこうなっていたとき、
hogefuga
というidがあると、後者のHogefuga
が使われる。(順番を逆にすると、
Hoge
のほうが使われてしまう)そのため、
hogefuga
の中にhoge
やfuga
が使われている場合には、先にhoge
やfuga
を含むコンポーネントを書いてあげよう。OKな例
頭の中で(ベン図のような)数学的な集合をイメージすれば、これなら問題ないと分かるはずである。
なぜなら、
hogefuga
を満たすためには、必要十分条件を満たす必要があるからだ。NGな例
この場合、
hogefuga
はFuga
でマウントされてしまう。