2017-09-15 75 views
1

无法从渲染器中调用函数。我的部分是:渲染器中的调用函数无法正常工作

class MyComp extends Component { 
    componentWillMount() { 
    this.props.getUsers(); 
    }; 

    getUsersfunction(users){ 
    return(
     console.log("i was called"); 
    users.map((user, idx) => { 
     return (
     <View key={idx}> 
      <Text style={styles.userNames}> ID: {user.id} - Name: {user.name} </Text> 
     </View> 
     ) 
     }); 
    ) 
    }; 


    render() { 
    console.log("USERS: ", this.props.users); 
    const { users } = this.props.users 

    return (
     <View style={styles.container}> 
     <ScrollView> 
      { users.length ? (
       {this.getUsersfunction(users)} // <= Is this the correct way? 
      ) : null } 
     </ScrollView> 
     </View> 
    ); 
    } 
} 

// mapStatetoProps and mapDispatchToProps here. 

export default connect(mapStateToProps, mapDispatchToProps) (MyComp); 

错误是this是一个保留字。 Console.log播放数组中的所有用户。我究竟做错了什么?

+0

'getUsersfunction'目前不返回任何东西。你可能想要添加一个return语句。 – Brian

+0

已更新的问题。这是我的错误。原始代码有回报。仍然没有返回。但控制台日志'“我被称为”' – Somename

回答

0

詹姆斯EMANON是相当正确的。

但是,如果我是你,我会移动逻辑来检查是否有东西要渲染或不进入函数本身。

getUsersfunction(){ 
    const { users } = this.props.users 

    if(!users) 
    return null; 

    return(
     console.log("i was called"); 
     users.map((user, idx) => { 
      return (
      <View key={idx}> 
       <Text style={styles.userNames}> ID: {user.id} - Name: {user.name} </Text> 
      </View> 
      ) 
     }); 
    ) 
}; 

然后,渲染变得干净多了:

<ScrollView> 
    {this.getUsersfunction()} 
</ScrollView> 

另一个重构,我建议是,既然你已经有了用户this.props你不需要通过PARAMS通过他们,所以你可以直接在你的功能中使用它。

绑定的功能也很重要,即使反应并不四个你,取决于你实际上是它可能会丢失上下文:

constructor() { 
    this.getUsersFunction = this.getUsersFunction.bind(this) 
} 

通过这种方式,您将不会收到错误,但如果你不能渲染用户,你将不得不开始评估是否真的需要渲染。

1

你不需要花括号:

{ users.length ? (
    this.getUsersfunction(users) // Now it's correct 
) : null } 
+4

要清楚;大括号表示何时要将JS插入到JSX上下文中。但是,一旦你已经在JS上下文中,大括号代表一个JSON对象。原始代码返回一个试图设置名为'this.getUsersfunction(users)'的变量的JSON对象,这显然不起作用。 – gravityplanx

+0

试过了。获取没有错误,但没有返回。但控制台日志'“我被称为”'。更新了有问题的功能。谢谢。 – Somename

+1

您需要从返回中删除控制台。将console.log语句放在返回之上 –

2

或者短一点,通过将这些花括号,您创建了一个不同的返回类型的对象,而不是你想要的JSX。

<ScrollView> 
    { users.length && this.getUsersfunction(users) } 
</ScrollView> 
0

你忘了bindgetUsersFunction方法在组件的构造:

constructor() { 
    this.getUsersFunction = this.getUsersFunction.bind(this) 
} 

render() { 
    const { users } = this.props.users 

    return (
    <View style={styles.container}> 
     <ScrollView> 
     { users.length && this.getUsersfunction(users) } 
     </ScrollView> 
    </View> 
) 
} 
0

你做const { users } = this.props.users

,但你应该做const { users } = this.props