gpt4 book ai didi

javascript - React Native 上子组件的 SetState 失败

转载 作者:行者123 更新时间:2023-12-01 02:43:04 26 4
gpt4 key购买 nike

我有一个子组件,它会触发父组件中的函数。虽然该函数被触发,但 setState 方法似乎抛出以下错误。

Possible Unhandled Promise Rejection (id: 0): undefined is not an object (evaluating '_this12.setState')

子组件:

return (
<View style={styles.buttonWrapper}>
<View style={styles.socialMediaButtonWrapper}>
<TouchableHighlight style={styles.socialMediaButtonBackFill} onPress={() => {
this.props.onFacebookAuthenticationPressed()
}}>
<View style={[styles.socialMediaButtonFill, {backgroundColor: '#5158bb'}]}>
<FontAwesome style={styles.socialMediaButtonTextIconFill} name="facebook" size={20}/>
</View>
</TouchableHighlight>
</View>
</View>
);

父组件(包括代码的子组件):

<FacebookLoginComponent
facebookAccessToken={this.state.facebookAccessToken}
onFacebookAuthenticationPressed = {this.onFacebookAuthenticationPressed}
/>

功能:

onFacebookAuthenticationPressed: function () {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(function (result) {
if (result.isCancelled) {
console.log("Login Cancelled");
} else {
console.log("Login Successful");
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken;
console.log(accessToken);
this.setState({
facebookAccessToken: accessToken
})
})
}
}, function (error) {
console.log("some error occurred!!");
}).done(() => {
this.markAsComplete();
})
},

我正在使用react-native-fbsdk用于身份验证的库。从 console.log 打印 token ,但 setState() 失败。

这是为什么呢?解决方法是什么?

最佳答案

子组件的小修复(不是必需的,但更好):

return (
<View style={styles.buttonWrapper}>
<View style={styles.socialMediaButtonWrapper}>
<TouchableHighlight style={styles.socialMediaButtonBackFill} onPress={this.props.onFacebookAuthenticationPressed}>
<View style={[styles.socialMediaButtonFill, {backgroundColor: '#5158bb'}]}>
<FontAwesome style={styles.socialMediaButtonTextIconFill} name="facebook" size={20}/>
</View>
</TouchableHighlight>
</View>
</View>
);

父组件的构造函数:

this.onFacebookAuthenticationPressed = this.onFacebookAuthenticationPressed.bind(this);

我不建议在渲染函数中使用bind。不过,你确实应该使用 ES6,React Native 已经提供了对此的支持。类属性而不是绑定(bind):

onFacebookAuthenticationPressed = () => {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then((result) => {
...
}, function (error) {
console.log("some error occurred!!");
}).done(() => {
this.markAsComplete();
})
};

...或者使用 ES5:

onFacebookAuthenticationPressed: function() {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(function (result) {
...
}.bind(this), function (error) {
console.log("some error occurred!!");
}).done(function() {
this.markAsComplete();
}.bind(this));
};

关于javascript - React Native 上子组件的 SetState 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47430485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com