反应:如何传递REST API的URL [英] react: how to pass in URLs for REST APIs
问题描述
开始学习反应,并在互联网上找不到答案.也许我不知道使用什么术语.
Starting to learn react and couldn't find the answer to this on the internet. Maybe I don't know what terms to use.
我的后端是django,我希望能够将REST API的URL传递到我的React前端.
我不想对它们进行硬编码,因为它们已经在django中定义.
对我来说,我想在我的html模板上呈现一个脚本标签,该脚本标签包含一个包含URL值的对象.
My backend is django and I want to be able to pass in URLs for REST APIs to my React front end.
I don't want to hard code them in react as they are already defined in django.
It makes sense to me that I would want to render a script tag on my html template that contains an object containing the URL values.
例如django模板会有类似的内容
e.g. the django template would have something like
<script type="text/javascript">
var CONFIG = {
some_url : '{% url "my-api" %}'
}
</script>
(对于不熟悉django的人,{%url%}标签会呈现类似/path/to/myapi的url)
(for those not familiar with django, that {% url %} tag renders a url like /path/to/myapi)
然后在我的React Stores/Actions中,我只引用CONFIG.some_url.
Then in my React Stores/Actions I would just refer to CONFIG.some_url.
这是正确的方法吗?还是有更好的方法使此信息可用于我的React组件.
Is this the right way to do it? Or is there a better way to make this information available to my react components.
------------编辑-----------------
------------ Edit -----------------
使用webpack转换jsx文件,并使用 django-webpack-loader 进行集成一切.这意味着在将jsx加载到顶部之前,将完全渲染django模板.
结果,模板标记无法在jsx文件内运行.
Using webpack to transpile the jsx files and using django-webpack-loader to integrate everything. this means that the django templates are completely rendered before the jsx is loaded on top.
As a result the template tags cannnot run inside the jsx files.
推荐答案
即使您使用的是django-webpack-loader(我也是),您仍然可以将prop传递给您的React应用.您可以这样进行:
Even though you're using django-webpack-loader(I am too), you still can pass props to your React app. You can proceed like this:
1)在您的view.py中解析绝对的后端URL:
1) Resolve the absolute backend url in your view.py:
def get_context_data(self, **kwargs):
context['APIROOT_URL'] = reverse('api-root', request=self.request)
return context
2)将上下文属性传递给html模板
2) Pass the context prop to the html template
<div id="react-app"></div>
<script>
window.__APIROOT_URL__= '{{ APIROOT_URL }}';
window.react_mount = document.getElementById('react-app');
</script>
{% render_bundle 'main' %}
3)最后,在您的应用程序内部,获取如下属性:
3) Finally inside your app, get the property like this:
const apirootUrl = window.__APIROOT_URL__
这篇关于反应:如何传递REST API的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!