无法使用 ReactNative fetch 获取数据 [英] Unable to get data using ReactNative fetch

查看:17
本文介绍了无法使用 ReactNative fetch 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 API 获取数据(我使用 JSON 服务器创建了自己的 Rest API).但我无法获取任何东西.但是,当我导航到 localhost:3000/events 时,我能够看到数据.我的应用程序中没有其他错误.我只有在运行应用程序时才得到这个,它说网络请求失败.所有组件都工作正常.就是拿不到数据.我尝试了其他一些在线 API 仍然没有得到任何响应.我试过异步/等待.我在 IOS 上使用该应用程序,但也尝试过使用 Andriod.出现同样的问题.附上代码片段.任何帮助将不胜感激.谢谢

I'm trying to fetch data from an API(I created my own Rest API using JSON-server). But I'm unable to fetch anything. however, I'm able to see the data when I navigate to localhost:3000/events. There's no other error in my app. I only get this when I run the app it says network request failed. All the components are working fine. Just not getting the data. I've tried some other online APIs still not getting any response. I've tried with async/await. I'm using the app with IOS but have tried with Andriod as well. Same problem occurs. Attaching the code snippets. Any help would be highly appreciated. Thanks

创建了 getEvent 函数:

Created the getEvent Function:

const { manifest } = Constants;
const api = manifest.packagerOpts.dev
  ? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
  : `api.example.com`;

const url = `http://${api}/events`;

export function getEvents() {
  return fetch(url)
  .then(response => response.json())
  .then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}

在 componentDidMount 中使用它

Using it inside the componentDidMount

componentDidMount() {
    // getEvents().then(events => this.setState({ events }));

    setInterval(() => {
      this.setState({
        events: this.state.events.map(evt => ({
          ...evt,
          timer: Date.now()
        }))
      });
    }, 1000);

    this.props.navigation.addListener("didFocus", () => {
      getEvents().then(events => this.setState({ events }));
    });
  }

我正在尝试获取的数据.

Data that I'm trying to fetch.

{
  "events": [
    {
      "title": "Demo a new app",
      "date": "2020-03-29T13:45:18.000Z",
      "id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
    }
  ]
}

推荐答案

你可以使用 axios 作为 fetch ,它也用于命中 API 并从它们那里获得响应,它简单而有效与获取相比的简单方法.

you can use axios as of fetch , it is also used to hit API's and get response from them , and it is simple and easy way as compare to fetch.

在你的项目 root floder 上运行 npm i react-native-axios 来安装库并导入并使用它,这里是一个 axios 的例子,其中用户将登录屏幕并点击登录 API,用户输入他们的凭据,如果它们在 API 中正确,那么用户将得到响应或用户将成功登录.

run npm i react-native-axios on your project root floder to install the library and import it and use it , here is an example of axios , in which the user will login to screen and will hit the login API , the user enter their credentials and if they are correct as in API then user will get response or user will login successfully.

    import axios from "axios";
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
      }
  };

  onPresssighnin = () => {
      var data = {
       //parameters to pass API
        Email: this.state.email,
        Password: this.state.password,
      };
      axios
        .post(" insert API url here", data, {
          "Content-Type": "application/json"
        })
        .then(
          response => {
           //get response here
            alert(JSON.stringify(response))
                      },
          error => {
            //get errormessage here
            errormessage = error.Message;
            alert(errormessage);
          }
        );
    }
  };
  render() {
      return (
              <View style={styles.logoContainer}>                
             <Input
                    borderless
                    placeholder="Email"
                    onChangeText={email => this.setState({ email })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="ic_mail_24px"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />
                  <Input
                    password
                    borderless
                    placeholder="Password"
                    onChangeText={password =>this.setState({ password })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="padlock-unlocked"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />

                    <Button
                      color="primary"
                      style={styles.createButton}
                      onPress={this.onPresssighnin} >
                      <Text bold size={14} color={ditsTheme.COLORS.WHITE}>
                        SIGN IN
                      </Text>
                    </Button>  
              </View>
      )
    }
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgb(32, 53, 70)',
    flexDirection: 'column',
  },
    buttonText: {
    textAlign: 'center',
    color: 'rgb(32, 53, 70)',
    fontWeight: 'bold',
    fontSize: 18
  }
})

不要怀疑.

这篇关于无法使用 ReactNative fetch 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆