未定义不是函数(评估“ navigation.dispatch”)

时间:2018-10-04 13:54:44

标签: react-native redux react-navigation

我正在尝试在用户注销后导航到第一页! 并得到此错误:

  

未定义不是函数(正在评估“ navigation.dispatch”)。

我的动作创建者代码如下:

import {NavigationActions} from 'react-navigation';
import {AsyncStorage} from 'react-native';
import {applyMiddleware as dispatch} from "redux";

export const userRemove = (navigation) => {
    AsyncStorage.removeItem('user');
    const navigateAction = NavigationActions.navigate({
        routeName: 'First',
        props: {}
    });
    navigation.dispatch(navigateAction);
};

我从组件的sideBar调用了此操作。组件代码是正确的,因为AsyncStorage.removeItem('user')正常工作! 对不起,语法不好。我的英语写得比这error message here

我的组件代码在这里:

import React, {Component} from 'react';
import {
    Container,
    Content,
    Footer,
    FooterTab,
    Button,
    Icon
} from 'native-base';
import {userRemove} from '../actions/sideBarAction';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";

class SideBar extends Component {
    constructor(props) {
        super(props);
    }

    logout() {
        userRemove(this.props.navigation);
    }

    render() {
        return (
            <Container>
                <Content>
                    ...
                </Content>
                <Footer>
                    <FooterTab>
                        <Button onPress={this.logout.bind(this)}>
                            <Icon name="logout"/>
                        </Button>
                    </FooterTab>
                </Footer>
            </Container>
        )
    }
}

const mapStateToProps = state => {
    return {
        username: state.home.username,
        password: state.home.password,
        score: state.home.score,
    }
};
const mapDispatchToProps = dispatch => {
    return Object.assign({dispatch: dispatch}, 
    bindActionCreators(userRemove, dispatch));
};

connect(mapStateToProps, mapDispatchToProps)(SideBar);

1 个答案:

答案 0 :(得分:1)

您的组件是否已添加到主导航器?如果看不到,是否可以添加。

您还可以使用withNavigation中的react-navigation函数包装组件。这将确保您具有有效的navigation道具。

import { withNavigation } from react-navigation;

...

connect(mapStateToProps, mapDispatchToProps)(withNavigation(SideBar));

或者,您也可以从父组件传递this.props.navigation