【问题标题】:How to pass variable in index.html to react components如何在 index.html 中传递变量以响应组件
【发布时间】:2019-02-27 01:36:24
【问题描述】:

我正在使用 Django 和 React 制作一个项目。我从 Django 的 Twitter API 获取数据,我想在前端显示数据。 我将 django views.py 中的数据作为 javascript 变量传递给 index.html。然后我想在 Components 文件夹中的 Landing.js 中展示它。我使用了 React 路由器,我的 Landing 和 Main page 是我目前路由到的页面。我还没有弄清楚如何将数据从单个 html 文件传递​​到 React 中的 Javascript 组件

提前致谢

<!-- index.html -->
<section class="section">
    <div class="container">
          <div id="app" class="columns"><!-- React --></div>
    </div>
  </section>
  <script type="text/javascript">
    window.myVar = "{{context.near.text}}";
    //data can be passed from the Django.views.py
    
  </script>

  {% load static %}
  <script src="{% static 'frontend/main.js' %}"></script>

//Landing.js js components
import React, { Component } from 'react';

class Landing extends Component {
    componentDidMount() {
        console.log(window.myVar); //undefined
        console.log(this.myVVar); //undefined
        
        
    }
    
    render(){
        return (
            <div>

                
                
            </div>
        )
    }
}

export default Landing;

This is my tree structure

this is context I pass from Django views.py

this is a variable I want to pass to "LANDING" componentsThis is "Landing.js" components I want to show the variables

【问题讨论】:

  • 这是可能的,但不要这样做——react 不是另一个模板引擎——让你的应用从你的 api 中获取数据
  • 我也有同样的问题。你想好怎么做了吗?

标签: javascript django reactjs


【解决方案1】:

index.html:

<script>
localStorage.setItem('data', data)
</script>

反应组件:

let data = localStorage.getItem('data')

【讨论】:

    【解决方案2】:

    window 对象中创建一个新属性,可能是window._DEFAULT_DATA,并将来自Django 的序列化数据传递给您的视图。

    在 HTML 的 head 标签中

    <script>
        window._DEFAULT_DATA = 'Data parsed in string'
     </script>
    

    然后当你想使用它时,只需使用JSON.parse 即可拥有一个新的 JSON。

    【讨论】:

    • 假设你想访问数据中的“tweets”字段,你必须像const data = JSON.parse(window._DEFAULT_DATA);一样解析并使用data.tweets访问
    • 在你设置好之后尝试使console.log(window._DEFAULT_DATA) 确保一切正常!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多