javascript - react native componetWillUpdate 不起作用

标签 javascript reactjs mobile react-native

我正在尝试使用状态中已有的数据(由 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)

最佳答案

componentWillReceiveProps 仅在组件渲染后、重新渲染组件之前更新 props 时调用。您需要在构造函数内设置状态,因为 Prop 应该已经在那里。

关于javascript - react native componetWillUpdate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44659823/

相关文章:

jquery - ontouchmove 事件获取 "this"?

Java 相当于 javascript 中的返回函数

javascript - 很好地格式化网格

javascript - React onClick 没有在第一次点击时触发,第二次点击按预期运行(简单的调试消息直到第二次点击才出现)

javascript - 矩形扩展中间件

reactjs - 如何开始使用 ReactJS Hello World 示例?

css - CSS 中的@media 查询

android - 解决 QString 移动错误

javascript - Laravel Dusk Javascript 确认()

javascript - 合并两个节点列表而不重复