简体   繁体   English

如何将 React Native 与 django rest api 连接

[英]How to connect React native with django rest api

I build a simple django rest api now i need to fetch data from it in frontend using React Native.我构建了一个简单的 django rest api 现在我需要使用 React Native 从前端获取数据。 I can make a request to the api but the data is not coming from there.我可以向 api 提出请求,但数据不是来自那里。 I search about it a lot but didn't find any help Thanks in advance...我搜索了很多但没有找到任何帮助提前谢谢...

npm install axios npm 安装 axios

const axios = require('axios')

export const App = () =>{
const Your_Request = () =>{
const config= {
method:'get',
url:'YOUR URL',
}
axios(config).then((response)=>{
console.log('response',response)
}).catch((error)=>{
console.log('error',error)})
}
return (<View></View>)
}

You should first try to see whether your API works correctly.您应该首先尝试查看您的 API 是否正常工作。 I can recommend you Postman ( https://www.postman.com/ ) for that.为此,我可以向您推荐 Postman ( https://www.postman.com/ )。 It's free, comes with an intuitive GUI, and allows you to make requests to your API, see the returned data, status codes, headers, and so on.它是免费的,带有直观的 GUI,并允许您向 API 发出请求,查看返回的数据、状态代码、标题等。

Once the API returns the data correctly, you'll need to fetch the data in the React application.一旦 API 正确返回数据,您需要在 React 应用程序中获取数据。 For that you can either place fetch() requests in the respective lifecycle methods, although this will get burdensome quite quickly if you need authentication, etc.. Another option would be to build service infrastructure using React hooks to share state (such as API tokens) across the component tree.为此,您可以将fetch()请求放在相应的生命周期方法中,尽管如果您需要身份验证等,这将很快变得繁琐。另一个选择是使用 React 挂钩构建服务基础架构以共享 state(例如 API 令牌) 跨组件树。 Here's a post I wrote on how to do that: https://schneider-lukas.com/blog/react-connect-rest-api .这是我写的关于如何做到这一点的帖子: https://schneider-lukas.com/blog/react-connect-rest-api

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM