无法使用ReactNative提取获取数据

问题描述 投票:1回答:1

我正在尝试从API提取数据(我使用JSON服务器创建了自己的Rest API)。但是我什么也拿不到。但是,当我导航到localhost:3000 / events时,我可以看到数据。我的应用程序中没有其他错误。当我运行表示网络请求失败的应用程序时,才得到此消息。所有组件都工作正常。只是没有得到数据。我尝试了其他一些在线API仍未得到任何响应。我已经尝试过异步/等待。我在IOS上使用该应用程序,但也尝试过Andriod。发生相同的问题。附加代码段。任何帮助将不胜感激。谢谢

创建了getEvent函数:

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内部使用

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 }));
    });
  }

我正在尝试获取的数据。

{
  "events": [
    {
      "title": "Demo a new app",
      "date": "2020-03-29T13:45:18.000Z",
      "id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
    }
  ]
}
react-native react-native-android react-native-ios
1个回答
0
投票

您可以在获取时使用axios,它也可以用来访问API并从中获取响应,并且与fetch相比,这是一种简单易行的方法。

install npm i react-native-axios安装库并导入并使用它,这是axios的示例,在该示例中,用户将登录到屏幕并点击登录API ,则用户输入其凭据,如果它们与API中的一样正确,则用户将获得响应或用户将成功登录。

    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
  }
})

毫无疑问。

© www.soinside.com 2019 - 2024. All rights reserved.