简体   繁体   中英

react native componetWillUpdate not working

I am trying to render a component with already existing data from state (provided from redux-persist), the data in is state.login.user (i can see it in console.log in the mapStateToProps function that is being called and returns the dataObject : state.login.user but the dataObject is not being updated and because of that componentWillReceiveProps is not being called.

Can you point me to what im doing wrong?

import React from 'react'
import { connect } from 'react-redux'
import { ScrollView, AppRegistry, Component, Text, Image, View, Button, Modal, TouchableOpacity } from 'react-native'
import { GiftedForm, GiftedFormManager } from 'react-native-gifted-form'

// Styles
import styles from './Styles/MyProfileScreenStyles'

class MyProfileScreen extends React.Component {
  constructor (props, context) {
    const dataObject = {
      profile: {
        last_name : undefined,
      }
    }
    super(props, context)
    this.state = {
      form: {
        lastName: dataObject.profile.last_name,
        tos: false
      }
    }
  }

  handleValueChange (values) {
    this.setState({form: values})
  }
  componentWillReceiveProps (newProps) {
    console.tron.log("componend will receive")
    console.tron.log(newProps)
    if (newProps.dataObject) {
      this.setState({
        dataObject: newProps.dataObject
      })
    }
  }
  render () {
    const {lastName, tos, gender} = this.state.form
    console.log('render', this.state.form)
    return (
      <View style={styles.container}>
        <GiftedForm
          formName='signupForm'
          openModal={(route) => { this.props.navigator.push(route) }}
          onValueChange={this.handleValueChange.bind(this)}
        >
          <GiftedForm.TextInputWidget
            name='lastName'
            title='Last name'
            placeholder='Last name'
            clearButtonMode='while-editing'
            value={lastName}
          />
          <GiftedForm.HiddenWidget name='tos' value={tos}/>
        </GiftedForm>
      </View>
    )
  }
}
const mapStateToProps = (state) => {
  if( state.login.user !== null){
    console.tron.log("test map state to props")
    return {
      dataObject: state.login.user
    }
  }
  return {}
}

export default connect(mapStateToProps)(MyProfileScreen)

componentWillReceiveProps is only called when the props are updated after the component has rendered, before the component is re-rendered. You'll want to set the state inside your constructor as the props should already be there.

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