当异步redux操作完成并且状态已更改时,如何重定向到其他屏幕?
我目前在我的应用程序中具有redux和react导航功能,并且我有以下代码来调度操作,获取令牌并将其存储为redux状态。当操作成功时(即this.props.isReady的状态更改为true),我想导航到StackNavigator中的新屏幕。但是我该怎么办?
import * as React from "react";
import { connect } from "react-redux";
import { fetchToken } from "./actions";
import { ActivityIndicator, View, Text } from "react-native";
import { Token } from "../../utils/interfaces";
import Styles from "../../theme/Styles";
export interface Props {
navigation: any;
token: Token;
isReady: boolean;
fetchToken(grantType: string, id: number, secret: string): object;
}
function bindAction(dispatch) {
return {
fetchToken: (grantType: string, id: number, secret: string) => dispatch(fetchToken(grantType, id, secret)),
};
}
const mapStateToProps = (state: any) => ({
token: state.setupReducer.token,
isReady: state.setupReducer.isReady,
error: state.setupReducer.error,
});
class SetupContainer extends React.Component<Props> {
state = {
message: "Etablerarar uppkoppling",
};
componentDidMount() {
this.props.fetchToken("client_credentials", XXXXXXXXX, "YYYYYYYYYYYYYYY");
}
render() {
if (this.props.isReady) {
return (
<View>
<ActivityIndicator size="large" color="#FF6600" />
<Text style={Styles.p}>{this.state.message}</Text>
</View>
);
}
return (
<View style={[Styles.marginY, Styles.p]}>
<Text style={Styles.p}>All done!</Text>
</View>
);
}
}
导出默认的connect(mapStateToProps,bindAction)(SetupContainer);
答案 0 :(得分:1)
您可以在componentDidUpdate中观看道具更改
componentDidUpdate(prevProps) {
if (!prevProps.isReady && this.props.isReady) {
// navigate
}
}
答案 1 :(得分:0)
您可以将导航对象传递给您的动作(例如this.props.fetchToken("client_credentials", XXXXXXXXX, "YYYYYYYYYYYYYYY",this.props.navigation)
),然后在分派后在动作内部使用导航对象进行导航。