【发布时间】:2023-03-04 03:46:02
【问题描述】:
我正在尝试使用 React Native 中的 Axios 从一个从 API 接收此信息并传递给正在接收并使用该上下文的另一个组件的上下文中获取包含一些用户数据的 API。
Axios API
import axios from 'axios';
export const api = axios.create({
baseURL: 'https://virtserver.swaggerhub.com/lucasstartab/euro-api/1.0.0'
})
上下文 API
export function AuthProvider(props) {
const [user, setUser] = useState(null);
async function signIn() {
try {
const response = await api.get('/user');
setUser(response.data[0].userInfo);
} catch(error) {
console.log(error);
}
}
return (
<AuthContext.Provider value={{signIn, user}}>
{props.children}
</AuthContext.Provider>
)
}
使用上下文的组件
export function UserInfo({ navigation }) {
const {user} = useContext(AuthContext);
return (
<ScrollView style={styles.container}>
<Host>
<View style={styles.padding}>
<View style={styles.header}>
<UserPhoto imageUri={user.foto} size='BIG' border={4}/>
<View style={styles.ProfileAndDesc}>
<Text style={styles.profile}>{user.name}</Text>
<Text style={styles.desc}>Filial {user.filial}</Text>
</View>
</View>
我不知道为什么会出现这个错误,我检查了 API URL,但它工作正常。错误:
在我的旅程中没有更多方法试图解决这个问题,希望得到答案,谢谢!
【问题讨论】:
-
从外观上看,可能没有名为“foto”的对象键。如果您提供一个指向 GitHub 存储库/gist 的链接并带有最少的工作代码以便更好地分析它,那就更好了。
-
这是我从 API url 得到的:
[ { "token": "a1b2c3", "userInfo": { "name": "Lucas", "email": "lucas@startab.com.br", "password": "Senha.123", "filial": "Sudeste", "foto": "https://github.com/lucastso.png", "fotoCapa": "https://images.unsplash.com/photo-1639208067515-99bccfacb05c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80" } } ]
标签: react-native axios react-context