【问题标题】:react native componetWillUpdate not working反应本机 componetWillUpdate 不起作用
【发布时间】:2017-06-20 17:45:57
【问题描述】:

我正在尝试使用 state 中已经存在的数据(由 redux-persist 提供)渲染组件,其中的数据是 state.login.user(我可以在正在调用的 mapStateToProps 函数的 console.log 中看到它并返回 dataObject : state.login.user 但 dataObject 没有被更新,因此没有调用 componentWillReceiveProps。

你能指出我做错了什么吗?

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)

【问题讨论】:

    标签: javascript reactjs mobile react-native


    【解决方案1】:

    componentWillReceiveProps 仅在组件渲染后更新道具时调用,在组件重新渲染之前。您需要在构造函数中设置状态,因为道具应该已经存在。

    【讨论】:

    • 如何给state.login.user设置props?
    • 在你的构造函数中定义一个dataObject,而你应该只使用props.dataObject
    • 在 this.state 中输入dataObject: props.dataObject
    猜你喜欢
    • 2016-07-20
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    相关资源
    最近更新 更多