2016-04-05 41 views
0

我在使用服务器端React来显示我的Mongo数据库中的玩家列表时遇到了问题。如何在服务器端React组件中使用回调值?

我的目标是从mongodbreact使用外部库一边,因为我想了解基本概念之前,我开始实施先进的解决方案。

我的代码需要一个模块(players.js)并调用index.jsx中定义的应该处理Mongo查询结果的回调函数。这些过程结果应该可以由组件访问。

这就是:

players.js

var MongoClient = require('mongodb').MongoClient; 

var url = 'mongodb://localhost/collection'; 
var database; 
var players; 

module.exports = function(callback) { 

    // Initialize collection 
    MongoClient.connect(url, function(err, db) { 
     database = db; 
     database.collection('players', findPlayers); 
    }); 

    // This named callback function is here in case 
    // I want to do anything else with the collection 
    function findPlayers(err, collection) { 
     collection.find({}, getCursor); 
    } 

    function getCursor(err, cursor) { 
     cursor.toArray(function(err, players) { 
      // Invoke callback with err and players array 
      callback(err, players); 

      // Close Mongo connection 
      database.close(); 
     }); 
    } 
} 

index.jsx

var React = require('react'); 
var players = require('./players'); 

// call module and pass processPlayers function 
var competitors = players(processPlayers); 

// with the query results, return some neat JSX code 
function processPlayers(err, results) { 
    return results.map(function(player) { 
     return (
      <tr> 
       <td>{ player.rank }</td> 
       <td>{ player.name }</td> 
      </tr> 
     ) 
    }); 
} 

// Create index component class 
var Index = React.createClass({ 
    render: function() { 
     return (<main><table>{ competitors }</table></main>); 
    } 
}); 

// Export component 
module.exports = Index; 

我明白,在index.jsx我设置competitors未定义的回报,但那是因为我卡住了。如何将competitors设置为映射结果?

再次,我是不是寻找承诺或异步库。 我想了解基础知识和正确的代码结构。如果提供了相关的库源代码,我甚至会很高兴。

谢谢!

回答

0

我发布了我的问题的答案。

我用于服务器端版本的React的库可以在here找到。

在文档中,我发现.jsx视图是同步的,建议我在路由中传递数据库查询结果。该数据将通过this.props作为组件中的一个属性公开。

所以...我走进我的路线文件,并更改从这个原代码:

module.exports = function (req, res) { 
    res.render('index'); 
} 

要这样:

var players = require('../helpers/players'); 

module.exports = function (req, res) { 
    // call to module with anonymous function callback 
    players(function(err, results) { 
     if (err) return console.log(err); 
     // using arg from anonymous function and 
     // passing as local variable 
     res.render('index', {'players': results}); 
    }) 
}; 

现在我的组件渲染方法看起来是这样的..

render: function() { 

    function createPlayerRows(player) { 
     return (
      <tr> 
       <td>{ player.rank }</td> 
       <td>{ player.name }</td> 
      </tr>   
     ); 
    } 

    // `players` property provided by route 
    // mapped array using callback function which 
    // creates an array of JSX elements 
    var players = this.props.players.map(createPlayerRows); 

    return (<main><table>{ players }</table></main>); 
} 

不知道它是否会帮助任何人出去,但我肯定松了一口气。

相关问题