最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Undefined is not a object in this.state - ReactNative - Stack Overflow

programmeradmin10浏览0评论

I'm new in ReactNative, I'm getting the error undefined is not a object in my this.state.rows I am trying to dynamically add a View when a user clicks a Button. I tried using this and instead of using getInitialState I used constructor(props) but I keep on having the said error. Here is my code

constructor(props) {
super(props);
this.state = {
  rows: [],
};
}

addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
}

render(){

let contactView = () => {
    return <View>
              <AddComponent />
           </View>
}

return(
 <View>
      <View>
        {contactView}
      </View>

      <TouchableHighlight onPress={ this.addRow } >
        <Text>Add</Text>
      </TouchableHighlight>
  </View>
);

Thank you for your help!

I'm new in ReactNative, I'm getting the error undefined is not a object in my this.state.rows I am trying to dynamically add a View when a user clicks a Button. I tried using this and instead of using getInitialState I used constructor(props) but I keep on having the said error. Here is my code

constructor(props) {
super(props);
this.state = {
  rows: [],
};
}

addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
}

render(){

let contactView = () => {
    return <View>
              <AddComponent />
           </View>
}

return(
 <View>
      <View>
        {contactView}
      </View>

      <TouchableHighlight onPress={ this.addRow } >
        <Text>Add</Text>
      </TouchableHighlight>
  </View>
);

Thank you for your help!

Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Mar 27, 2017 at 6:56 natsumiyunatsumiyu 3,2579 gold badges34 silver badges54 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 19

You need to bind this to the function addRow like this:

<TouchableHighlight onPress={ this.addRow.bind(this) } >
  <Text>Add</Text>
</TouchableHighlight>

or create an anonymous function to automatically bind this:

<TouchableHighlight onPress={ () => this.addRow() } >
  <Text>Add</Text>
</TouchableHighlight>

For explanation refer to this.

You can do this too.

export default class CustomCard extends React.Component{
    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.functionName= this.handleUpvote.bind(this);
    }
}

For calling the function you can call it like this.

<TouchableHighlight onPress={this.functionName} >
  <Text>Add</Text>
</TouchableHighlight>
<TouchableHighlight onPress={ this.addRow.bind(this) } >
  <Text>some text</Text>
</TouchableHighlight>
发布评论

评论列表(0)

  1. 暂无评论