【问题标题】:React Redux - Get value of Redux state and update local stateReact Redux - 获取 Redux 状态的值并更新本地状态
【发布时间】:2018-09-02 17:12:49
【问题描述】:

我有以下更新状态的代码。我将必填字段的值存储在 - mandatory_fields

class CompleteProfile extends Component {
  state = {
    completeProfileNeeded: false,
  }

  componentDidMount = () => {
    let { dispatch, session } = this.props
    dispatch(getMandatoryFields(session.username))
  }

使用dispatch(getMandatoryFields(session.username))更新Redux状态如下图所示

我的 mapstatetoprops 是:

const mapStateToProps = state => ({
  mandatory_fields: state.User.mandatory_fields,
  session: state.User.session,
})

如何从mandatory_fields获取性别、宗教和年龄的值,如果它们没有如上所示的值,请更新completeProfileNeeded: true

【问题讨论】:

  • 你需要调度另一个动作,它会用新的信息更新reducer。
  • 您的代码似乎不需要状态。 mapState 中的一切似乎都是可计算的。

标签: reactjs redux


【解决方案1】:

值为mapped from state to props,gender 将在this.props.mandatory_fields.gender 之下。

您可以使用 componentDidUpdate 来检查值是否已定义并更新状态,但这必须是防止循环的条件操作。

正如 Mas 所说,它 (completeProfileNeeded) 可以在地图状态下计算并与其他值一起传递。

您也可以在条件渲染中直接使用其中的部分(或全部)值,而无需将其设置为 state 中的值。

【讨论】:

  • 谢谢。我将代码更改为在从数据库获取值的地方计算 completeProfileNeeded。这样我的有效载荷只有completeProfileNeeded true/false。 redux 中的这种状态正在更新,但 this.props.mandatory_fields.completeProfileNeeded 始终是 true。我期望只有当 redux 状态为真时它才会为真。
  • 不更新mapStateToProps?在mandatory_fields 下方/内部,比如gender?使其成为单独的值,redux 可能不会对更深层次的变化做出反应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 2021-01-08
  • 2020-08-07
  • 2018-03-20
相关资源
最近更新 更多