Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 与模板引擎反应_Node.js_Reactjs_Express - Fatal编程技术网

Node.js 与模板引擎反应

Node.js 与模板引擎反应,node.js,reactjs,express,Node.js,Reactjs,Express,您好,我决定用ReactJS NodeJS(ExpressJS)等创建一个项目。在我学会使用React之前,我使用的是模板引擎(Mustache),我的配置就是这样 app.engine('html', consolidate.mustache); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); 但让我困惑的是我在电视上看到的这段代码 他们没有使用任何模板引擎,但如何从服务器获取呈现变量 @jake

您好,我决定用ReactJS NodeJS(ExpressJS)等创建一个项目。在我学会使用React之前,我使用的是模板引擎(Mustache),我的配置就是这样

app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
但让我困惑的是我在电视上看到的这段代码


他们没有使用任何模板引擎,但如何从服务器获取呈现变量

@jake你可以参考Jhipster生成器()
它有助于使用基本模板生成React JS应用程序。

您不必在视图中发送所有变量,甚至任何变量。在RESTful应用程序中,客户机的任务是查询信息以便稍后显示

在服务器代码中,您将有两类路由。第一个用于服务HTML页面,第二个用于从服务器获取和更改内容

为html页面提供服务的路由:

app.get('/', function(req, res){
    res.sendFile(path.resolve('views/index.html'));
});

app.get('/login', function(req, res){
    res.sendFile(path.resolve('views/login.html'));
});
从服务器获取和更改变量的路由:

app.get('/api/variable1', function(req, res){
    var variable1 = getFromDatabase('variable1'); //get variable from database
    res.send(variable1); //send variable to front-end
});

app.post('/api/modifyVariable1', function(req, res){
    var newValue = req.body.variable1;
    modifyVariableInDatabase('variable1', newValue); //modify value in database
    res.send({success: true}); //send acknowledgement to client
});
在react前端,您将查询变量并相应地更新状态以更新视图

getVariable1(){
    fetch("/api/variable1")
      .then((response) => {
        return response.json();
      }).then((json) => {
        this.setState({variable1: json}); //update 'variable1' in our state
      }).catch((err) => {console.log(err);});
}
如果您希望直接将变量与视图一起发送,那么您将在React:in
componentDidMount()
lifecycle方法中尽快获得它

componentDidMount(){
    this.getVariable1();
}

我希望这对您有意义。

据我所知,react只创建SP应用程序,我如何能够同时使用索引和登录html,以及如果我想要诸如“Hello USERNAME”之类的问候语,我如何在不渲染的情况下获得该用户名?您可以为每个页面创建react脚本。在index.html上,您将使用'index script.js',在login.html上使用'login script.js'。您必须使用呈现,您将编写
Hello{this.state.username}
,并将使用第二类路由之一从您的服务器查询
username
。在这种情况下,我应该使用componentWillMount吗?我想,我是否正确地执行异步操作(例如对服务器的请求)在
中,组件将装入
将是一个问题。相反,在设置
this.state.username
值之前,您可能希望显示占位符数据,或者什么也不显示。
componentDidMount(){
    this.getVariable1();
}