Reactjs 将新状态传递给React中的子组件

Reactjs 将新状态传递给React中的子组件,reactjs,react-redux,Reactjs,React Redux,我用动作法连接了家用组件道具,并成功地调度了减速器。一切似乎都很好,我可以看到Api数据来到控制台中的reducer 问题是,react不会重新呈现ProfileGroupsWidget。在这个子组件中,this.props.user始终是{},我希望它是{name:John Doe} 这是userReducer,GET_AUTH_USER_成功来自getAuthenticatedUser: 主页是我的主页组件: 在代码中,this.props.user始终是未定义的,因为您没有在reducer

我用动作法连接了家用组件道具,并成功地调度了减速器。一切似乎都很好,我可以看到Api数据来到控制台中的reducer

问题是,react不会重新呈现ProfileGroupsWidget。在这个子组件中,this.props.user始终是{},我希望它是{name:John Doe}

这是userReducer,GET_AUTH_USER_成功来自getAuthenticatedUser:

主页是我的主页组件:

在代码中,this.props.user始终是未定义的,因为您没有在reducer中为其设置值。我们必须按以下方式设置值:

编辑代码:

编辑代码: 在主组件中:在MapStateTrops中,我将userReducer维护为标识符,请将其更改为在rootReducer中使用的任何reducer名称

如果您愿意,我们还可以完全删除构造函数代码,并将动作分派移动到componentWillMount

在代码中,this.props.user始终是未定义的,因为您没有在reducer中为其设置值。我们必须按以下方式设置值:

编辑代码:

编辑代码: 在主组件中:在MapStateTrops中,我将userReducer维护为标识符,请将其更改为在rootReducer中使用的任何reducer名称

如果您愿意,我们还可以完全删除构造函数代码,并将动作分派移动到componentWillMount


为什么要将props.user传递到您所在的州?根据您当前的代码,这应该是不必要的。这样,最好将this.props.user直接分配给ProfileGroupsWidget。也就是说,如果redux正常工作并正确连接到组件

另外,最好在componentDidMount中调用网络请求或操作,而不是在构造函数中调用:

componentDidMount() {
  this.props.getAuthenticatedUser();
}
如果所有内容都正确,则应该看到this.props.user的多个console.logs,如果您将其记录在渲染中:

render() {
  console.log(this.props.user);
  /*
    should be called at least twice,
    the last one containing the data {name: "John Doe"}
  */

  return (
    <ProfileGroupsWidget user={this.props.user}></ProfileGroupsWidget>
  )
  ...

为什么要将props.user传递到您所在的州?根据您当前的代码,这应该是不必要的。这样,最好将this.props.user直接分配给ProfileGroupsWidget。也就是说,如果redux正常工作并正确连接到组件

另外,最好在componentDidMount中调用网络请求或操作,而不是在构造函数中调用:

componentDidMount() {
  this.props.getAuthenticatedUser();
}
如果所有内容都正确,则应该看到this.props.user的多个console.logs,如果您将其记录在渲染中:

render() {
  console.log(this.props.user);
  /*
    should be called at least twice,
    the last one containing the data {name: "John Doe"}
  */

  return (
    <ProfileGroupsWidget user={this.props.user}></ProfileGroupsWidget>
  )
  ...

谢谢…但是比props.user总是{}。我还尝试在componentDidMount中调用。在构造函数中,props.user将始终为空,因为在reducer的初始状态中,user为空。在构造函数/componentWillMount中调用getAuthenticatedUser后,将调度操作并设置用户,在后续呈现中,您可以看到console.logthis.props.user;//{name:John Doe}谢谢。我不知怎的把你的答案和Tyro Hunter的答案结合起来解决了这个问题。谢谢你…但是比props.user总是{}。我还尝试在componentDidMount中调用。在构造函数中,props.user将始终为空,因为在reducer的初始状态中,user为空。在构造函数/componentWillMount中调用getAuthenticatedUser后,将调度操作并设置用户,在后续呈现中,您可以看到console.logthis.props.user;//{name:John Doe}谢谢。我不知怎么把你的答案和蒂罗·亨特的答案结合起来解决了这个问题。谢谢。现在它起作用了。同时,我还添加了一个加载道具,它只在reducer设置了值之后才会呈现小部件。谢谢。现在它起作用了。同时,我还添加了一个加载道具,该道具仅在reducer设置值后才呈现小部件。
componentDidMount() {
  this.props.getAuthenticatedUser();
}
render() {
  console.log(this.props.user);
  /*
    should be called at least twice,
    the last one containing the data {name: "John Doe"}
  */

  return (
    <ProfileGroupsWidget user={this.props.user}></ProfileGroupsWidget>
  )
  ...