ユーザーの情報を表示するために使用するダンプ コンポーネントがあるとします。ユーザー情報をコンポーネントに渡す方法は 2 つあります。
1):
class UserItem extends PureComponent {
// pass user's properties
const {
userName, userEmail,
} = this.props;
// same
render() {
return (
<View>
<Text>{userName}</Text>
<Text>{userEmail}</Text>
</View>
);
}
}
2):
class UserItem extends PureComponent {
// pass a user object
const {
userName, userEmail,
} = this.props.user;
// same
render() {
return (
<View>
<Text>{userName}</Text>
<Text>{userEmail}</Text>
</View>
);
}
}
では、どの方法を使用すればよいですか?私が知っているいくつかの長所と短所を 2 つの方法でリストします。
1)
長所:
ロジックは非常に理解しやすく、「魔法のような」ことは起こらず、渡されたものは何でもコンポーネントに表示されます。
浅い比較状態と小道具 ( https://reactjs.org/docs/shallow-compare.html )によって PureComponent のパワーを使用できるため、コンポーネントは必要なときにのみ再レンダリングされます。
短所:
次のように、渡す多くのパラメーターを入力する必要があり
<UserItem userName={user.name} userEmail={user.email}>
ます (spreading operator を使用しない限り...user
、すべてのオブジェクト プロパティを渡します)。コンポーネント内でオブジェクト メソッドを使用できません。たとえば、
user.totalMoneys()
オブジェクトには遅延計算されたプロパティがいくつかあるため、 User モデルには method があります。
2)
長所:
渡すのは簡単に見えます:
<UserItem user={user}>
UserItem 内でオブジェクト メソッドを使用できます
短所:
- PureComponent の利点を使用できず、自分自身を比較する必要があります。