React类组件中map函数内无法访问state变量的问题求助
解决React类组件map回调中无法访问this.state的问题
Hey,这个问题我熟!你遇到的TypeError: Cannot read properties of undefined (reading 'state')是因为map回调里的this指向不对,而且你把.bind(this)放错位置啦 😄
问题根源
当使用普通function作为map的回调函数时,函数内部的this不会自动绑定到组件实例上。而你之前把.bind(this)调用在了map返回的数组上——这完全起不到绑定回调this的作用,因为bind是Function.prototype的方法,必须绑定到回调函数本身才能生效。
修复方案
方案1:使用箭头函数(最简洁推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是组件实例的this),这样就能直接访问this.state了:
<Pagination> {this.state.total > 0 ? Array(Math.ceil(this.state.total / 10)).fill(0).map((object, i) => { return <Pagination.Item active={false} key={i}>{i + 1}</Pagination.Item> }) : null} </Pagination>
方案2:给map的回调函数直接绑定this
把.bind(this)绑定到map的回调函数上,而不是数组结果:
<Pagination> {this.state.total > 0 ? Array(Math.ceil(this.state.total / 10)).fill(0).map(function (object, i) { return <Pagination.Item active={false} key={i}>{i + 1}</Pagination.Item> }.bind(this)) : null} </Pagination>
方案3:在构造器中提前绑定回调(适合复杂逻辑复用)
如果分页项的渲染逻辑比较复杂需要复用,可以在构造器里提前绑定回调函数的this,再在render中使用:
constructor(props) { super(props); this.state = { page: 2, total: 0, }; // 提前绑定回调的this到组件实例 this.renderPaginationItem = this.renderPaginationItem.bind(this); } renderPaginationItem(object, i) { return <Pagination.Item active={false} key={i}>{i + 1}</Pagination.Item>; } // 在render中调用 <Pagination> {this.state.total > 0 ? Array(Math.ceil(this.state.total / 10)).fill(0).map(this.renderPaginationItem) : null} </Pagination>
内容的提问来源于stack exchange,提问作者George Raveen
相关产品推荐
相关产品推荐

