【问题标题】:undefined is not a function (evaluating 'fetch('apiurl')')undefined 不是函数(评估 'fetch('apiurl')')
【发布时间】:2017-11-06 17:26:21
【问题描述】:

我使用的是以下版本

  1. react-native-router-flux ^3.39.1
  2. react-native 0.44.0

我希望它会调用我与“获取”一起使用的 API 已使用 componentDidMount 但它显示另一个错误

undefined 不是对象(评估 'this._component.getScrollableNode')

但我的输出低于错误输出

复制步骤

  1. 使用路由器通量创建三个场景(在我的例子中是应用、登录、主页)
  2. 使用 ScrollView 创建 Login.js 创建按钮
  3. 使用 TouchableHighlight 之后使用函数调用 fetch 使用 onPress 像 onPress={ () => this.fetchData() }

下面的代码,我用于 App.js

import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    AsyncStorage,
} from 'react-native';

import Login from './components/Login'
import Register from './components/Register'
import Home from './components/Home'
import { Scene, Router, TabBar, Modal, Schema, Actions, Reducer, ActionConst } from 'react-native-router-flux'

const reducerCreate = params=>{
    const defaultReducer = Reducer(params);
    return (state, action)=>{
        console.log("ACTION:", action);
        return defaultReducer(state, action);
    }
};

export default class App extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            logged: false,
            loading: true,
        };
    };

    componentWillMount(){
        self = this;
        AsyncStorage.getItem('token')
        .then( (value) =>{
            if (value != null){
                this.setState({
                    logged: true,
                    loading: false,
                });
            }
            else {
                this.setState({
                    loading: false,
                })
            }
        });
    };

    render() {
        if (this.state.loading) {
            return <View><Text>Loading</Text></View>;
        }
        return (
            <Router>
                <Scene hideNavBar={true} key="root">
                    <Scene key="logIn" component={Login} title="Login" initial={!this.state.logged}/>
                    <Scene key="regisTer" component={Register} title="Register"/>
                    <Scene key="home" component={Home} title="home"  initial={this.state.logged}/>
                </Scene>
            </Router>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});

下面的代码,用于 Login.js

/* @flow */

import React, { Component } from 'react';

import {
    View,
    StyleSheet,
    Image,
    ScrollView,
    TextInput,
    Text,
    TouchableHighlight,
    Alert,
} from 'react-native';
import { Container, Content, InputGroup, Input, Icon, Item } from 'native-base';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import ResponsiveImage from 'react-native-responsive-image'

export default class Login extends Component {

    constructor(props){
        super(props)
        this.state = {
            email: '',
            password: '',
            data: '',
        }
    }

    fetchData() {
        fetch('http://allstariq.tbltechnerds.com/api/login/?username=andress&password=23434')
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                data: responseData.movies,
            });
        })
        .done();
    }

    render() {
        return (
            <View style={styles.container}>

            <ScrollView>

                <View style={ styles.logoContainer }>

                    <View style={{flexDirection: 'row',}}>
                        <ResponsiveImage
                        source={require('../assets/logo.png')}
                        initWidth="300"
                        initHeight="160" />
                    </View>

                </View>

                <View style={ styles.formContainer }>
                    <Item>
                        <Icon active name='mail' />
                        <Input
                            onChangeText={(text) => this.setState({email: text})}
                            value={this.state.email}
                            placeholder='Email'/>
                    </Item>

                    <Item>
                        <Icon active name='key' />
                        <Input
                            onChangeText={(text) => this.setState({password: text})}
                            value={this.state.password}
                            placeholder='Password'/>
                    </Item>
                    <TouchableHighlight
                        style={ styles.loginButton }
                        onPress={ () => this.fetchData() }>
                        <Text style={ styles.btnText}>Login</Text>
                    </TouchableHighlight>
                </View>

                <View style={ styles.bottomContainer }>
                    <Text style={ styles.cenText }>Dont worry if you haven't an account yet . . </Text>
                    <Text
                    style={ styles.blueText}
                    onPress={ Actions.regisTer }
                    >Register Now</Text>
                </View>

            </ScrollView>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    logoContainer: {
        flex: .5,
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
    },
    logoItem: {
        width: null,
        height: null,
        resizeMode: 'cover',
    },
    formContainer: {
        flex: 4,
        padding: 10,
    },
    inputelm: {
        marginBottom: 10,
        backgroundColor: '#999',
        borderWidth: 0,
        fontSize: 20,
        color: '#FFF',
        fontFamily: 'AmaticSC-Bold',
    },
    loginButton: {
        borderRadius: 3,
        marginBottom: 20,
        marginTop: 20,
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: '#2196f3',
        elevation: 4,
    },
    signupButton: {
        borderRadius: 3,
        marginBottom: 20,
        marginTop: 20,
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: '#7cb342',
        elevation: 4,
    },
    btnText: {
        textAlign: 'center',
        color: '#FFF',
        fontSize: 30,
        lineHeight: 40,
    },
    blueText: {
        textAlign: 'center',
        color: '#2196f3',
        fontSize: 20,
        lineHeight: 40,
    },
    bottomContainer: {
        flex: 1,
        padding: 10,
    },
    cenText: {
        textAlign: 'center',
        fontSize: 16,
    },
});

在 react-native-router-flux 中使用 fetch 的实际方法是什么?我是新手,请帮助我。

【问题讨论】:

  • 添加您编写的代码将有助于获得答案
  • @ShubhamKhatri 更新了代码

标签: reactjs react-native react-native-router-flux


【解决方案1】:

好吧,这晚了几个月,但这里的问题是您的 fetchData 方法无法访问它,因为当您声明这样的方法时:

fetchData() {

}

在后台,react 是以这种方式创建一个函数:

this.fetchData = function() {

}

当您使用 function 关键字声明函数时,{} 之间的所有内容都将拥有自己的“this”,您的方法将无法访问组件上下文的“this”。

这就是你得到“未定义”的原因,因为你在 fetch 返回的承诺中调用了“this.setState”,所以错误不是 fetch,而是 this。

要解决这个问题,你可以这样定义你的方法:

fetchData = () => {

}

由于用粗箭头定义的函数不会创建自己的范围,因此组件“this”将在您的方法内部可用。

【讨论】:

    【解决方案2】:

    您是否尝试过导入库?

    Import fetch from "fetch";
    

    【讨论】:

      【解决方案3】:

      你还没有导入fetch函数,从node-fetch模块中导入就好

      import fetch from 'node-fetch'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-30
        • 2019-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-05
        • 1970-01-01
        相关资源
        最近更新 更多