【问题标题】:How to navigate when redux state changes?redux 状态变化时如何导航?
【发布时间】:2019-12-10 20:41:03
【问题描述】:

当我的异步 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>
        );
    }
}

导出默认连接(mapStateToProps, bindAction)(SetupContainer);

【问题讨论】:

    标签: reactjs react-native react-redux react-navigation expo


    【解决方案1】:

    你可以在 componentDidUpdate 中观察 props 的变化

     componentDidUpdate(prevProps) {
         if (!prevProps.isReady && this.props.isReady) {
           // navigate
         }
     }
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2023-03-23
      • 2019-07-07
      • 2019-10-30
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多