簡體   English   中英

如何在meteor.js和react.js上編寫一個簡單的聊天,沒有數據庫?

[英]How to write a simple chat, without a database on meteor.js and react.js?

我想在meteor.js上寫一個簡單的聊天,因此我不想將數據存儲在database 但我從未發現如何在沒有database情況下創建應用程序。

這是我能想象的代碼示例。 服務器代碼:

export let ws = [{_id:'1', text:'test1'}, {_id:'2', text:'test2'}];
Meteor.publish('ws', function wsPub() { return ws; });
let ctr = 3;
Meteor.methods({
    'addMsg'(text) {  ws.push({_id:ctr+1, text:text});  }
});

和客戶代碼:

import {ws} from '../api/model.js';

class Rtc extends Component {
  constructor(props) {
    super(props);
  }
  addMsg(e){
    e.preventDefault();
    Meteor.call('addMsg', this.refs.input.value);
  }
  render() {
    return (
      <div>
         {this.props.ws.map((item, i)=>{ 
           return(<span key={i._id}>{item.text}</span>); 
         })}
         <input type="text" ref="input" />
         <input type="submit" value="submit" onClick={this.addMsg.bind(this)}/>
       </div>
    );
  }
}
export default createContainer( () => {
  Meteor.subscribe('ws');
  return { ws: ws };
}, Rtc);

但我不明白我在createContainer寫的不是這樣嗎?

UPD:我更新了服務器代碼,但仍然無法使用websockets:

Meteor.publish('ws', function wsPub() {
  let self = this;
  ws.forEach( (msg)=> {
    self.added( "msg", msg._id, msg.text );
  });
  self.ready();
  // return ws;
});

你認為不會起作用。 因為Meteor.publish返回一個光標到一個CollectionarrayCollections 根據官方文件

發布函數可以返回Collection.Cursor,在這種情況下,Meteor會將該游標的文檔發布到每個訂閱的客戶端。 您還可以返回一組Collection.Cursors,在這種情況下,Meteor將發布所有游標。

同樣,當您訂閱發布時,它會在MiniMongo中本地存儲數據(作為游標與發布相同的集合)。 因此,在Meteor中使用pub-sub技術上無法進行無數據庫的聊天。

如果要控制通過發布發送的內容,請獲取對“發布實例”(實際上是具有特定訂閱的特定客戶端)的引用,並使用其add / change / remove命令:

let messages = [];
let clients = [];
Meteor.publish('ws', function() {
    clients.push(this);
    _.each(messages, (message) => {this.added('msg', message._id, message);});
    this.ready();
});
Meteor.methods({
    addMsg(text) {
        let newMessage = {_id: Meteor.uuid(), text: text};
        messages.push(newMessage);
        _.each(clients, (client) => {client.added('msg', newMessage._id, newMessage);});
    }
});

關於您在更新中編寫的代碼:您正在發送一個string ,其中added的函數需要文檔( object )。 此外,與上面的示例不同,您不會在ws (消息數組)發生更改時告訴客戶端。

我建議也將這些東西重命名為更詳細和清晰:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM