【问题标题】:Pass id from redux into state of component将 id 从 redux 传递到组件的状态
【发布时间】:2017-12-01 07:12:56
【问题描述】:

这是我的组件的状态:

 state = {
          data: {
            userId: `${user.id}`,
            name: '',
            country: '',
            city: ''
        },
        loading: false,
        errors: {}
       };

我使用 redux 从登录用户中检索用户 ID:

function mapStateToProps(state){
  return{
    user: state.user
  }
}
QuestForm.propTypes = {
  user:PropTypes.shape({
    email: PropTypes.string.isRequired
  }).isRequired,
  submit: PropTypes.func.isRequired
};

export default connect(mapStateToProps, null)(Form);

它向我抱怨'user' is not defined no-undef

状态内的语法或我的 redux 逻辑方法是否有问题? 提前谢谢!

【问题讨论】:

  • 你有codepen什么的?
  • 无法明确回答。例如您的状态 sn-p .. 用户变量来自哪里?您的组件源不完整。如果您的状态 sn-p 是组件状态还是 redux 状态,它也不完全清楚。因为你写了state of my component 我假设组件状态。设置依赖于你的道具的状态也是一种反模式。
  • 你能贴出你的组件的代码,在哪里定义状态?
  • @JuHwon,我想将用户从 redux 传递到组件的状态。这个组件不是为用户准备的,而是为游戏准备的。我这样做的唯一原因是在 API 调用之后保存该游戏是由该特定用户创建的。除了将 id 作为表单的一部分传递之外,我没有找到另一种在 api 调用中将 userId 作为参数传递的方法。

标签: reactjs redux store


【解决方案1】:

${user.id} 应该是 ${props.user.id}${this.props.user.id},具体取决于您是否有基于类或函数的组件。

user 未定义,因为这不是您访问道具的方式:)

【讨论】:

  • ${this.props.user.id} 正在工作。但我不确定我明白为什么。因为在我的逻辑中,我是从function mapStateToProps(state) 调用user,认为我可以通过这种方式从redux store 中获取任何元素。现在看来,不需要 redux 来获得用户。因为您的解决方案意味着我只使用简单的反应。我说的对吗?
  • 名称mapStateToProps 实际上会告诉您发生了什么,它会获取您从该函数返回的任何内容并将其作为props 传递,在您的情况下,它返回具有属性user 的对象,即然后在 props 上可用,访问 props 的方法是使用 this.props 和您从类基组件上的 mapStateToProps 返回的属性名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2016-08-31
  • 2021-04-11
  • 2019-02-17
相关资源
最近更新 更多