React-Native之undefined is not an object

前端之家收集整理的这篇文章主要介绍了React-Native之undefined is not an object前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

刚学习rn,有很多不理解的地方,常常会报undefined is not an object这个错,然后在不断的修改和试错的情况下
,发现只要发生这个情况就有this存在,先贴出一段错误代码

export default@H_502_6@ class@H_502_6@ Test@H_502_6@ extends@H_502_6@@H_502_6@ Component@H_502_6@ {@H_502_6@
    constructor(props) {
        super@H_502_6@(props)
        this@H_502_6@.state = {
            header: "我是header"@H_502_6@,_data: [
                {key: 'a'@H_502_6@},{key: 'b'@H_502_6@},{key: 'c'@H_502_6@},{key: 'd'@H_502_6@},]
        }
    }

    _header() {
        return@H_502_6@ (
            <Text style={{backgroundColor: "red"@H_502_6@,height: 100@H_502_6@,}}>
                {this@H_502_6@.state.header}
            </Text>
        );
    }

    render() {
        return@H_502_6@ (
            <View>
                <FlatList
                    ListHeaderComponent={this@H_502_6@._header}//header头部组件@H_502_6@
                    data={this@H_502_6@.state._data}
                    renderItem={({item}) => <Text style={{alignSelf: "center"@H_502_6@,flex: 1@H_502_6@,height: 30@H_502_6@}}>{item.key}</Text>}
                />
            </View>
        );
    }
}

报错如图

说是this.state.header这地方错误,刚接触这些很郁闷,引用state里面的值不都是这么引入的吗,
我试着写了个简单的demo

export default@H_502_6@ class@H_502_6@ Test@H_502_6@ extends@H_502_6@@H_502_6@ Component@H_502_6@ {@H_502_6@
    constructor(props) {
        super@H_502_6@(props)
        this@H_502_6@.state = {
            header: "我是header"@H_502_6@,}
    }

    render() {
        return@H_502_6@ (
            <View>
                <Text>{this@H_502_6@.state.header}</Text>
            </View>
        );
    }
}

完全是可以的,这让我这个初入rn的初学者头疼了,后来我想,会不会和这个this有关呢,
我试着删除{this.state.header},随便加点固定值,是完全可以的,后来我想,这个_header函数是FlatList组件的
一个子组件,会不会是_header()函数的this指向的是FlatList组件呢?我要如何拿到全局的this呢?
后来看了下资料,找到了解决方法,就是给_header()函数绑定全局的this,默认的this是指向是父组件的

export default@H_502_6@ class@H_502_6@ Test@H_502_6@ extends@H_502_6@@H_502_6@ Component@H_502_6@ {@H_502_6@
    constructor(props) {
        super@H_502_6@(props)
        this@H_502_6@.state = {
            header: "我是header"@H_502_6@,]
        }
        //将全局的this绑定到_header函数@H_502_6@
        this@H_502_6@._header=this@H_502_6@._header.bind(this@H_502_6@)
    }

    _header() {
        return@H_502_6@ (
            <Text style={{backgroundColor: "red"@H_502_6@,height: 30@H_502_6@}}>{item.key}</Text>}
                />
            </View>
        );
    }
}

总结

1、子组件指向的this属于子组件,与父组件无关 2、子组件不能去父组件更新状态 3、如果要在子组件更新父组件的状态,给子组件绑定父组件的this

猜你在找的React相关文章