我卡住了,不知道如何跨屏幕传递 API 响应数据。
在屏幕#1中,我进行API调用并获取响应数据 现在我需要使用响应数据中的 api-secret "密钥"到注销屏幕。
我正在阅读有关Redux的信息,但感到困惑,无法完全理解它。
寻找一些替代方法,我可以传递数据。
我的代码是
class Login extends Component {
constructor(props) {
super(props);
this.state = {
user: {
login: "",
password: ""
},
activity: false
};
}
_login = async () => {
if (this.state.user.login !== "" && this.state.user.password !== "") {
console.log(this.state);
this.setState({ activity: true });
await Axios.post(LoginAPI, this.state, { headers: { appversion: 1.4 } })
.then(response => {
console.log(response);
const status = response.status;
if (status === 200) {
this.setState({ activity: false });
this.setState({ response });
this.props.navigation.navigate("CreateMove");
console.log(this.state);
}
})
.catch(error => {
console.log({ error });
this.setState({ activity: false });
Alert.alert("Error", error.response.data.error);
});
//Alert.alert("Easymove", "Login ");
//this.props.navigation.navigate("CreateMove");
} else {
Alert.alert("Support", "Email & Password field can not be empty");
}
};
}
并且需要跨屏幕传递状态响应
你已经在使用 react 导航,所以你可以将响应作为带有路由名的参数传递,或者使用 setParam 和 getParam https://reactnavigation.org/docs/en/params.html
this.props.navigation.navigate("CreateMove", { response: response});
在您的另一个屏幕中,您将获得以下响应
const response = this.props.navigation.getParam('response')
由于您不想在应用程序中使用 redux,因此请在 React Native 中使用 AsyncStorage。
首先,安装npm i @react-native-community/async-storage
。 然后更改您的_login
功能,如下所示。不要同时使用 Promise 和 Async/Await,而只使用一种方法。
import AsyncStorage from '@react-native-community/async-storage';
_login = async () => {
if (this.state.user.login !== "" && this.state.user.password !== "") {
this.setState({ activity: true });
try {
let response = await Axios.post(LoginAPI, this.state, {
headers: { appversion: 1.4 }
});
if (response.status == 200) {
this.setState({
activity: false,
response
});
await AsyncStorage.setItem('@Secret-Key', response);
this.props.navigation.navigate("CreateMove");
}
} catch (error) {
this.setState({ activity: false });
Alert.alert("Error", error.response.data.error);
}
} else {
Alert.alert("Support", "Email & Password field can not be empty");
}
};
然后从注销屏幕获取@Secret-Key
值。
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem("@Secret-Key");
if (value !== null) {
// You can access your data
}
} catch (error) {
console.log(error);
}
};
希望这对你有帮助。随意怀疑。