如何解决如何在React Native中解决错误``cb不是函数''?
当前代码
Index.js
import Auth from 'app/src/common/Auth';
export default class Index extends React.Component {
async componentDidMount() {
this.props.navigation.addListener('willFocus',Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
}));
}
...
}
Auth.js
import axios from 'axios';
import { ENV } from 'app/env';
import { AsyncStorage } from 'react-native';
const { baseApiUrl } = ENV;
export default {
async me() {
try {
let result = false;
let token = await AsyncStorage.getItem('token');
token = token.replace(/"/g,'');
const response = await axios.get(`${baseApiUrl}/api/auth/me`,{
headers: {
Authorization: `Bearer ${token}`,},});
if (response.data) {
result = true;
}
return result;
} catch (error) {
console.log(error);
}
},};
错误
我不断收到此错误。
TypeError:cb不是函数。 (在“ cb(数据)”中,“ cb”是Promise的一个实例)
如果您能给我任何建议,我将不胜感激。
解决方法
如果没有详细的代码知识(或做出反应),很难说出来,但是从我的名字来看,我希望this.props.navigation.addListener
会使用callback
函数。相反,您会兑现承诺。
this.props.navigation.addListener('willFocus',Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
})
);
尝试将代码更改为:
this.props.navigation.addListener('willFocus',() => {
Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
})
});
,
编辑:对于当前问题,@ kai答案更好(并且更正确)。我会留下答案,但是在setState函数上使用async / await仍然是错误的
您应该从setState中删除$ minikube mount <source directory>:<target directory>
:
<Tab.Navigator
tabBarOptions={{
activeTintColor: '#0093cb',keyboardHidesTabBar:true,style: {
// Remove border top on both android & ios
borderTopWidth: 1,borderTopColor: "#999999",},}
}
>
<Tab.Screen name="Wallet" component={Wallet StackScreen}
options={{
tabBarLabel: 'Wallet',tabBarIcon: ({ color,size }) => (
<Ionicons name='ios-filing' color={color} size={size}/>),),}}
/>
<Tab.Screen name="Settings" component={Settings}
options={{
tabBarLabel: 'Settings',size }) => (
<Ionicons name='ios-settings' color={color} size={28}/>),}}
/>
</Tab.Navigator>
通过使用await
,Javascript有望实现承诺。但是this.props.navigation.addListener('willFocus',Auth.me()
.then((response) => {
this.setState({ isLoggedIn: response });
})
);
不会返回函数。
在旁注中,如果需要等待setState函数的应用,则可以将回调用作第二个参数:
await
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。