How do I insert a Django template variable into a React script?

前端 未结 1 339
悲哀的现实
悲哀的现实 2020-12-05 12:31

I am using Django Rest Framework with React.js. My page shows one user\'s profile, using an api like this:

http://localhost:8000/api/profile/[pk]

<
相关标签:
1条回答
  • 2020-12-05 12:43

    When you render the component, you should pass the pk as a prop.

    <script>
    React.render(React.createElement(Profile, {
        userId: "{{ userId }}", 
        urlPrefix: "/api/profile/" 
    }), element);
    </script>
    

    A better alternative might be to just fetch the user, and then render the component. For example, with superagent:

    superagent.get('/api/profile/{{ userId }}', function(res){
        React.render(React.createElement(Profile, 
            {user: res.body}
        ), element);
    });
    

    With browserify, you can either include data in a script tag, and use that in your code:

    <script>var _appData = {userId: "{{ userId }}"};</script>
    

    Or export modules using the -r flag (.require() in the api).

    # sh
    browserify -r react -r src/profile.js:profile.js
    
    // js
    b.require('react').require('src/profile.js', {expose: 'profile.js'});
    

    And then use the modules in regular script tags

    <script>
    var React = require('react');
    var Profile = require('profile.js');
    
    React.render(React.createElement(Profile, {
        userId: "{{ userId }}", 
        urlPrefix: "/api/profile/" 
    }), element);
    </script>
    
    0 讨论(0)
提交回复
热议问题