2016-02-19 106 views
1

我真的想把自己的脑袋绕过属性,以及它们是如何通过反应的。但我不能。无论我尝试什么,我都无法访问任何我传入组件的内容。React原生属性

我有一个主页,它包含一个MyProfile组件,即Im将JSON对象传递给用户属性。

var myUser = {"name":"test","avatar":"imagelinketc"} 

<MyProfile user={myUser} /> 

然后在MyProfile组件中,Im根据传递的属性设置用户。但它不工作!?

class MyProfile extends Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     user: props.user, 
     loaded:false 
    }; 
    } 

    render(){ 
    return(
     <View> 
     <Text>{this.state.user.name}</Text> 
     </View> 
    ) 
    } 
} 

这将返回null/undefined。

然后我尝试这个...

class MyProfile extends Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     user: null, 
     loaded:false 
    }; 
    } 

    onComponentWillMount(){ 
    this.setState({ 
     user:this.props.user,  
     loaded:true 
    }); 
    } 

    render(){ 
    return(
     <View> 
     <Text>{this.state.user.name}</Text> 
     </View> 
    ) 
    } 
} 

仍不明确。 我也试过了,直接设置this.user属性。在this.state之外,仍然未定义。看来我无法将属性传递给MyProfile。无论我传递什么,结果都是空的。我是否完全倒退?

如何将用户从第一页传递到配置文件页面?一直坚持了几个小时。 PS:我实际上已经能够在我的应用程序中的其他地方传递属性就好了。 并使用它们传递给组件。它只是这一种成分,让我悲痛

+0

您不应该手动设置状态。 – christopher

+0

详细说明。我一直在做这个遍布我的应用程序,它迄今为止工作。我应该如何设置状态? (不使用flux,redux动作等)该应用程序很简单,直到我将所有数据加载到顶部,并将其传递到需要它的页面。到目前为止,它一直在努力。很明显,尽管我完全错了。仍然在考虑常规应用程序,而不是反应流量。 PS所有的例子似乎确切地说明了我在这里完成的工作,所以我不确定你说的意思是什么时候不要手动设置 – KyleK

+0

你可以传递View和Text组件吗? – necromos

回答

3

有你需要做的几件事情:

  1. 变化onComponentWillMount到componentWillMount

  2. 当传承的属性和它们设置在构造函数,你需要引用它们this.props而不是道具

看看下面的代码,看看我在说什么:

var user = { name: 'Chris', age: 22, location: 'California' } 

class App extends Component { 

    constructor(props){ 
    super(props) 
    this.state = { 
     user: user 
    } 
    } 

    render() { 
    return (
     <View style={styles.container}> 
     <User user={ this.state.user } /> 
     </View> 
    ); 
    } 
} 

class User extends Component { 
    constructor(props){ 
    super(props) 
    this.state = { 
     user: this.props.user 
    } 
    } 

    render() { 
    return <View> 
       <Text>{ this.props.user.name }</Text> 
       <Text>{ this.props.user.age }</Text> 
       <Text>{ this.props.user.location }</Text> 
      </View> 
    } 
} 
+1

谢谢!解决了! – KyleK