こんにちは、
私はreact-nativeでreduxを使用していますが、これまでのところ素晴らしいです!
私のアプリにはユーザープロファイルがあり、状態は次のようになります。
{
users: {
"1": {id: "1", name: "Ran"},
"2": {id: "2", name: "Dan"}
}
}
これで、シングルユーザーをレンダリングする<Profile>
コンポーネントができました。
class Profile extends React.Component {
componentDidMount() {
const { dispatch, userId } = this.props;
dispatch(loadUser(userId));
}
render() {
console.log(this.props.user.name);
}
}
コンポーネントがマウントされると、 userId
をpropとして渡してloadUser
アクションをディスパッチします。
これにより、APIにリクエストが送信され、 users
状態にユーザーレスポンスが追加されます。
ここで、プロファイルコンポーネントが、小道具としてレンダリングするユーザーを受け取るようにします。
だから基本的に私は次のようなことをしたいです:
function mapStateToProps(state) {
return {
user: state.users[props.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
私は小道具にアクセスできないので、明らかにそれは機能しません。
ナビゲーションスタックで複数のプロファイルをレンダリングしているため、 selectedProfile
ような状態を使用してフィルタリングすることはできません。それぞれに異なるuserIdがあり、グローバルなselectedProfile状態を使用すると、戻るボタンが壊れます。
私が見つけた唯一の回避策は、 ProfileContainer
コンポーネントを作成することです。これは、その小道具で状態をフィルタリングし、単一のユーザーをProfile
コンポーネントに渡します。
class ProfileContainer extends React.Component {
render() {
let user = this.props.users[this.prop.userId];
return <Profile user={user} />
}
}
それは意味がありますか? 他の誰かがこの問題に遭遇しますか?
ありがとう、
走った。
ねえ、
これはもっとreact-reduxの問題です...何かが足りないかもしれませんが、私には非常に単純に思えます。mapStateToPropsに渡される「ownProps」引数を使用すると、上記のコードは次のようになります。
function mapStateToProps(state, ownProps) {
return {
user: state.users[ownProps.userId]
};
}
module.exports = connect(mapStateToProps)(Profile);
あなたは間違いなくコンポーネントの小道具にアクセスできます。 それはどのように見えますか? 詳細については、 https: //github.com/rackt/react-redux#connectmapstatetoprops -mapdispatchtoprops-mergeprops-optionsまたはhttps://github.com/rackt/redux/blob/master/examples/real-world/containers/を参照してUserPage.js ...
見逃したなんて信じられない! ありがとう@alanrubin
:いいぞ:
今後、このような問題をreact-reduxに提出してください。
このリポジトリとは関係ありません。
最も参考になるコメント
ねえ、
これはもっとreact-reduxの問題です...何かが足りないかもしれませんが、私には非常に単純に思えます。mapStateToPropsに渡される「ownProps」引数を使用すると、上記のコードは次のようになります。
あなたは間違いなくコンポーネントの小道具にアクセスできます。 それはどのように見えますか? 詳細については、 https: //github.com/rackt/react-redux#connectmapstatetoprops -mapdispatchtoprops-mergeprops-optionsまたはhttps://github.com/rackt/redux/blob/master/examples/real-world/containers/を参照してUserPage.js ...