加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React-Native之undefined is not an object

发布时间:2020-12-15 06:44:58 所属栏目:百科 来源:网络整理
导读:刚学习rn,有很多不理解的地方,常常会报undefined is not an object这个错,然后在不断的修改和试错的情况下 ,发现只要发生这个情况就有this存在,先贴出一段错误的代码 export default class Test extends Component { constructor(props) { super (props

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

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

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

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

报错如图

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

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

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

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

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

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

总结

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读