Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

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

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]

I want to dynamically set the url for the react ajax request to include the proper pk, so that it requests the correct user's information from the server.

I could use a function like window.location.href and pop the number from the end, but is there a way to do this by passing the pk directly from the server, i.e., using a template variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...