2017-06-20 121 views
0

我想呈現一個組件已經存在的數據從狀態(從redux持久提供),數據在state.login.user(我可以看到它在console.log中的mapStateToProps正在被調用,並返回的dataObject功能:state.login.user但dataObject時沒有被更新,因爲componentWillReceiveProps的不被稱爲反應原生componetWillUpdate不工作

你可以點我什麼即時做錯了

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) 

回答

2

componentWillReceiveProps僅在組件已渲染後更新道具時調用, nt被重新渲染。您需要在構造函數中設置狀態,因爲道具應該已經在那裏。

+0

你如何設置道具到state.login.user? – AleXzpm

+0

在你的構造函數中,你應該只使用'props.dataObject'來定義'dataObject'。 – Jwebbed

+0

在this.state中放入'dataObject:props.dataObject' –