【问题标题】:Cannot read property 'navigate' of undefined - React Native无法读取未定义的属性“导航”-React Native
【发布时间】:2018-09-14 06:22:27
【问题描述】:

我是 React-Native 的新手。我只是不断收到与“无法读取未定义的属性'导航'”相同的错误。这是示例代码

export default class Form extends Component {
    constructor(props) {
        super(props);
        this.loginHandler = this.loginHandler.bind(this);
        this.navigate  = this.props.navigation;
        this.successCallback = this.successCallback.bind(this);
        this.state = {
            email: '',
            password: '',
        }
    }

    // TODO - Login Authentication
    loginHandler() {
        var loginUrl = 'someURL';
        fetch(loginUrl, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: this.state.email,
                password: this.state.password
            }),
        })
            .then(response => { return response.json(); })
            .then(responseData => { return responseData; })
            .then((responseData) => {
                this.successCallback(responseData.token)
            })
            .catch((err) => { console.log(err); });

    }

    successCallback(token) {
        if (token === undefined)
            alert("Email or password is incorrect !");
        else {
            this.props.navigation.navigate('User', {tokenFromUser: token});
        }

}

在 successCallback 函数中,如果生成了令牌,则表示登录凭据正确,因此应使用参数“令牌”导航到 UserScreen。谁能帮我 ?

这是我如何调用 loginHandler 函数

        <TouchableOpacity style={styles.button} onPress={this.loginHandler} >
            <Image source={loginImage} style={styles.image} />
            <View style={styles.SeparatorLine} />
            <Text style={styles.text}>
                Enter
            </Text>
        </TouchableOpacity>

【问题讨论】:

  • 你的Form注册导航了吗?
  • 是的。我也试过了。在我的 App.js 文件中,我添加了 Form.js。但是我使用这个 Form.js 作为组件而不是屏幕
  • 如果您的 Form.js 是一个组件,请尝试使用 hoc 包装器作为 this 进行导航或从父文件传递导航道具

标签: react-native navigation


【解决方案1】:

嗯,我找到了我猜的解决方案。在我调用 Form.js 组件的地方,我只是添加了 {...this.props} 作为道具。

<Form {...this.props}   />

这样是因为 Form.js 的 props 是空的。

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多