简体   繁体   中英

React Redux - Get value of Redux state and update local state

I have the following code that updates the state. I am storing values of mandatory fields in - mandatory_fields

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

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

The Redux state is updated as shown below using dispatch(getMandatoryFields(session.username))

在此处输入图片说明

My mapstatetoprops is :

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

How can I get the value of gender, religion and age from mandatory_fields and if they have no value as shown above, update completeProfileNeeded: true

Values are mapped from state to props , gender will be under this.props.mandatory_fields.gender .

You can use componentDidUpdate to check if values are defined and update state but this has to be conditional action to prevent loop.

As Mas stated it ( completeProfileNeeded ) can be computed in map state and passed with other values.

You can also directly use some (or all) of these values in conditional rendering without setting this as value in state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM