0

ユーザーに関するデータを取得するために API をクエリして、React/Redux アプリを構築しています。

ここでチュートリアルを再利用しようとしています: https://rackt.org/redux/docs/advanced/ExampleRedditAPI.html

特定のユーザーの情報を表示するコンテナー コンポーネント UserPage があるとします。

class UserPage extends Component {
  componentWillMount() {
    this.props.dispatch(fetchUser(this.props.user.id));
  }

  render() {
    <UserProfile name={this.props.user.name} />
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    user: _.find(state.users, (user) => user.id == ownProps.params.userId)),
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    dispatch
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(UserPage);

現在のユーザーを取得するために、API 呼び出しを行います。 GET /api/users/:userId

私の問題は、コンポーネントを初期化するときに、プロパティ user が必ずしも存在しないことです。

そのため、エラーが表示されますcan't call property name on undefined

コンポーネントの初期状態をどのように処理しますか? componentWillReceivePropsUI の更新に依存していますか? プロパティを使用していisFetchingますか?

ありがとうございました!

4

1 に答える 1