React Native组件内访问状态:点击RkButton更新state的实现问题
问题分析与解决方案
嘿,我知道你卡在哪了!你在MainRoutes.map里用了普通的function作为回调,这会导致回调函数里的this指向不是你的组件实例,自然就没法调用this.setState来更新状态啦。
给你几个简单的解决办法,选一个你顺手的就行:
方法1:使用箭头函数作为map的回调
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的组件实例),这样就能正常访问this.setState了:
render() { const { user } = this.props; let navigate = this.props.navigation.navigate; // 把map的回调改成箭头函数 let items = MainRoutes.map((route, index) => { return ( <RkButton rkType='square' key={index} onPress={() => { this.setState({ redeem: true }); }}> </RkButton> ) }); return ( <View style={{flex: 1,}}> <ScrollView alwaysBounceVertical={true}> {/* 你的其他页面内容 */} </ScrollView> </View> ) }
方法2:给map的回调函数绑定this
如果习惯用普通function,可以在回调后面用.bind(this)把组件实例的this绑定进去:
render() { const { user } = this.props; let navigate = this.props.navigation.navigate; let items = MainRoutes.map(function (route, index) { return ( <RkButton rkType='square' key={index} onPress={() => { this.setState({ redeem: true }); }}> </RkButton> ) }.bind(this)); // 绑定组件的this到回调函数 return ( <View style={{flex: 1,}}> <ScrollView alwaysBounceVertical={true}> {/* 你的其他页面内容 */} </ScrollView> </View> ) }
方法3:提前保存this到变量里
在render开头把组件的this存到一个变量(比如that),然后在回调里用这个变量访问setState:
render() { const { user } = this.props; let navigate = this.props.navigation.navigate; const that = this; // 提前保存组件实例的this let items = MainRoutes.map(function (route, index) { return ( <RkButton rkType='square' key={index} onPress={() => { that.setState({ redeem: true }); }}> </RkButton> ) }); return ( <View style={{flex: 1,}}> <ScrollView alwaysBounceVertical={true}> {/* 你的其他页面内容 */} </ScrollView> </View> ) }
简单说下核心原因:普通的function在被map调用时,它的this默认指向全局对象(严格模式下是undefined),根本不是你的组件实例,所以调用this.setState会报错或者没反应。上面的三种方法都是为了让回调里能正确拿到组件实例的this,这样就能正常更新状态啦!
内容的提问来源于stack exchange,提问作者SwimmingG
相关产品推荐
相关产品推荐

