问题
I am new to React and experimenting a bit. I would like to use it on my Flask site that uses Jinja2 templates.
People seem to recommend to render data on the server-side first instead of having to always make an initial call for data on page load. I found this nodejs example but it just puts the data on the page in a global variable in an inline script tag. I was wondering if there was a clean way to do this other than just putting the data on the page inside an inline script tag. Because of my secure CSP policy I can't use inline scripts or eval.
Is there an standard pattern people use to render data for React on the server without using an inline variable?
回答1:
You can certainly use it on sites that have server side rendering via Jinja. The question becomes - what do you want to update on the page without reloading? Usually, the component state in React is updated via user interaction or a changing data source (i.e. db API).
My experience has been to render (via Jinja) the static page data and then use React components to update based on and/or listen for changes to the state of an API (maybe through Flask-Restful). These APIs can be accessed through React's life cycle methods (usually 'getInitialState' or 'setState')
For example - you may have portions of your site that are rendered server-side in layout.html
and then the {% block content %}
is rendered client side by the React js components.
{% extends "layout.html" %}
{% block content %}
<h2>Some Header</h2>
<script type="text/jsx" src="/scripts/ReactComponent1.js">
</script>
<div id="one">
<!-- This element's contents will be replaced with ReactComponent1. - ->
</div>
<script type="text/jsx" src="/scripts/ReactComponent2.js">
</script>
<div id="two">
<!-- This element's contents will be replaced with ReactComponent2. -->
</div>
{% endblock %}
I really recommend going through the React Tutorial and trying to apply it to a Flask App.
来源:https://stackoverflow.com/questions/32705233/how-to-use-jinja2-server-side-rendering-alongside-react-without-violating-inline