我需要从 API 获取用户 ID,然后将其附加到变量上,这样我就可以将其导出,然后将其用作其他对象中的值。有人可以帮我举个例子吗?我该怎么做?我只坚持在控制台上显示它。
这是我的代码:
class LoginScreen extends Component {
constructor(){
super();
this.state = {
email: '',
password: '',
id: 0,
result: false,
}
}
_userLogin() {
let email = this.state.email;
let password = this.state.password;
if (email && password) {
fetch("https://URL/api/login", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password,
})
})
.then((response) => {
if(response.status !== 200) {
throw new Error('The given data was invalid.')
}
return response.json();
})
.then((responseData) => {
this.renderResults(responseData)
console.log(responseData)
this.props.navigation.navigate('IntroScreen');
})
.catch((err) => console.log(err.message))
}
}
componentDidMount () {
fetch("https://URL/api/login", {
method: "GET",
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({getId: responseJson});
console.log(responseJson.data.id);
const id = responseJson.data.id;
})
.catch((error) => {
console.error(error);
});
}
renderResults = (responseData) => {
if(responseData){
this.setState({
result: true
})
}
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
errorMessage = () => {
Alert.alert(
'Error',
'The given data was invalid.',
[
{
text: "OK",
style: "cancel"
},
],
{ cancelable: false }
)
}
render() {
return (...)
将它附加到变量后,我想在其他对象中使用它,例如:
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
currentDate: new Date(),
markedDate: moment(new Date()).format("YYYY-MM-DD"),
isLoading: true,
id: 1, <------- HERE
name: '',
floor: 0
};
}