Reactjs 每秒更新来自api的消息

Reactjs 每秒更新来自api的消息,reactjs,react-native,axios,state,Reactjs,React Native,Axios,State,我正在我的react native mobile应用程序中为我的聊天界面使用react native gifted chat,在我的组件中将挂载我从api获取用户的消息并将其呈现在gifted chat界面中,gifted chat中发送的任何消息也将发送到api,该api将消息保存在db中。现在我想每秒更新一次消息状态,这样当其他用户也向当前用户发送消息时,我会尝试使用set interval,但模拟器总是挂起,请问除了我所做的之外,更新消息数组的最有效方法是什么 constructor(p

我正在我的react native mobile应用程序中为我的聊天界面使用
react native gifted chat
,在我的组件中将挂载我从api获取用户的消息并将其呈现在gifted chat界面中,gifted chat中发送的任何消息也将发送到api,该api将消息保存在db中。现在我想每秒更新一次消息状态,这样当其他用户也向当前用户发送消息时,我会尝试使用set interval,但模拟器总是挂起,请问除了我所做的之外,更新消息数组的最有效方法是什么

 constructor(props) {
    super(props);
    this.state = {
        messages: []
    };
    this.checker = this.checker.bind(this);
};
checker(){
    const {params} = this.props.navigation.state;
           this.setState({loading: true});
           var bodyParameters = {
               id: params.id,
               receiver_id: params.receiver_id
           }
          /*    var config = {
               headers: {'Authorization': "Bearer " + this.state.token}
          };*/
          axios.post(
              'http://10.0.2.2:8000/api/messages',
              bodyParameters,
          //      config
          ).then((response) => {
           this.setState({loading: false});
           console.log(response);   
           var len = response.data.success?response.data.success.length:null;
           for (let i = 0; i < len; i++) {
               let row = response.data.success[i];
               console.log(row.id, row.user1.id);console.log("chat")
               this.setState(prevState => ({
                   messages: [...prevState.messages, {_id: row.id, text: row.message, 
                       createdAt: row.created_at, user: {_id: row.user1.id,name: row.user1.first_name+' '+row.user1.last_name}}],
               }), console.log(this.state.messages));
               console.log("checker");
           };
          }).catch((error) => {
           this.setState({loading: false}); 
                   console.log(error); 
                  });      
}
componentDidMount(){
this.interval = setInterval(() => this.checker(), 1000);
}
componentWillUnmount() {
        clearInterval(this.interval);
      }
componentWillMount() {
    const {params} = this.props.navigation.state;
 /*   var pusher = new Pusher('1363556f717d953dcf86', {
        cluster: 'mt1',
        forceTLS: true
      });
      var channel = pusher.subscribe('private-messages.'+ params.id);
      channel.bind('MessageSent', function(data) {
        console.log(data);
      });*/
        this.setState({loading: true});
        var bodyParameters = {
            id: params.id,
            receiver_id: params.receiver_id
        }
    /*    var config = {
            headers: {'Authorization': "Bearer " + this.state.token}
       };*/
       axios.post(
           'http://10.0.2.2:8000/api/messages',
           bodyParameters,
     //      config
       ).then((response) => {
        this.setState({loading: false});
        console.log(response);   
        var len = response.data.success?response.data.success.length:null;
        for (let i = 0; i < len; i++) {
            let row = response.data.success[i];
            console.log(row.id, row.user1.id);console.log("chat")
            this.setState(prevState => ({
                messages: [...prevState.messages, {_id: row.id, text: row.message, 
                    createdAt: row.created_at, user: {_id: row.user1.id,name: row.user1.first_name+' '+row.user1.last_name}}],
            }), console.log(this.state.messages));
            console.log("contjii");
        };
       }).catch((error) => {
        this.setState({loading: false});
            Alert.alert(
                'Error',
                 'Internal Server Error, please try again later',
                [
                  {text: 'OK'},
                ],  );    
                console.log(error); 
               });    
 /*   this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 1,
            name: 'React Native',
            avatar: 'https://placeimg.com/140/140/any',
          },
      //    image: 'https://facebook.github.io/react/img/logo_og.png',
          // additional custom parameters
          sent : true,
          received : true,
        },
      ],
    })*/
  }

  onSend(messages = []) {
      console.log(messages);
      const {params} = this.props.navigation.state;
      messages[0].sent = true;
    var bodyParameters = {
        id: params.id,
        receiver_id: params.receiver_id,
        message: messages[0].text
    }
/*    var config = {
        headers: {'Authorization': "Bearer " + this.state.token}
   };*/
   axios.post(
       'http://10.0.2.2:8000/api/sendMessage',
       bodyParameters,
 //      config
   ).then((response) => {
    this.setState({loading: false});
    console.log(response);   

   }).catch((error) => {
    this.setState({loading: false});
        Alert.alert(
            'Error',
             'Internal Server Error, please try again later',
            [
              {text: 'OK'},
            ],  );    
            console.log(error); 
           }); 
      this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }));  
  }
render() {
    const {params} = this.props.navigation.state;
    return (
<GiftedChat
        messages={this.state.messages}
       //  inverted={false}
        onSend={messages => this.onSend(messages)}
        user={{
          _id: params.id,
        }}
      />
 );
 }
构造函数(道具){
超级(道具);
此.state={
信息:[]
};
this.checker=this.checker.bind(this);
};
检查器(){
const{params}=this.props.navigation.state;
this.setState({loading:true});
变量bodyParameters={
id:params.id,
接收方id:params.receiver\u id
}
/*变量配置={
标题:{'Authorization':“Bearer”+this.state.token}
};*/
轴心柱(
'http://10.0.2.2:8000/api/messages',
车身参数,
//配置
)。然后((响应)=>{
this.setState({loading:false});
控制台日志(响应);
var len=response.data.success?response.data.success.length:null;
for(设i=0;i({
messages:[…prevState.messages,{u id:row.id,text:row.message,
createdAt:row.created_at,用户:{{u id:row.user1.id,name:row.user1.first_name+''+row.user1.last_name}}],
}),console.log(this.state.messages));
控制台日志(“检查程序”);
};
}).catch((错误)=>{
this.setState({loading:false});
console.log(错误);
});      
}
componentDidMount(){
this.interval=setInterval(()=>this.checker(),1000);
}
组件将卸载(){
clearInterval(这个.interval);
}
组件willmount(){
const{params}=this.props.navigation.state;
/*var推进器=新推进器('1363556f717d953dcf86'{
群集:“mt1”,
forceTLS:对
});
var channel=pusher.subscribe('private-messages.'+params.id);
channel.bind('MessageSent',函数(数据){
控制台日志(数据);
});*/
this.setState({loading:true});
变量bodyParameters={
id:params.id,
接收方id:params.receiver\u id
}
/*变量配置={
标题:{'Authorization':“Bearer”+this.state.token}
};*/
轴心柱(
'http://10.0.2.2:8000/api/messages',
车身参数,
//配置
)。然后((响应)=>{
this.setState({loading:false});
控制台日志(响应);
var len=response.data.success?response.data.success.length:null;
for(设i=0;i({
messages:[…prevState.messages,{u id:row.id,text:row.message,
createdAt:row.created_at,用户:{{u id:row.user1.id,name:row.user1.first_name+''+row.user1.last_name}}],
}),console.log(this.state.messages));
控制台日志(“contjii”);
};
}).catch((错误)=>{
this.setState({loading:false});
警惕,警惕(
“错误”,
'内部服务器错误,请稍后再试',
[
{文本:'确定'},
],  );    
console.log(错误);
});    
/*这是我的国家({
信息:[
{
_id:1,
文本:“你好,开发者”,
createdAt:新日期(),
用户:{
_id:1,
名称:“反应本机”,
阿凡达:'https://placeimg.com/140/140/any',
},
//图像:'https://facebook.github.io/react/img/logo_og.png',
//其他自定义参数
是的,
收到:是的,
},
],
})*/
}
onSend(消息=[]){
控制台日志(消息);
const{params}=this.props.navigation.state;
消息[0]。已发送=真;
变量bodyParameters={
id:params.id,
接收方id:params.receiver\u id,
消息:消息[0]。文本
}
/*变量配置={
标题:{'Authorization':“Bearer”+this.state.token}
};*/
轴心柱(
'http://10.0.2.2:8000/api/sendMessage',
车身参数,
//配置
)。然后((响应)=>{
this.setState({loading:false});
控制台日志(响应);
}).catch((错误)=>{
this.setState({loading:false});
警惕,警惕(
“错误”,
'内部服务器错误,请稍后再试',
[
{文本:'确定'},
],  );    
console.log(错误);
}); 
this.setState(previousState=>({
消息:giftechat.append(previousState.messages,messages),
}));  
}
render(){
const{params}=this.props.navigation.state;
返回(
this.onSend(messages)}
使用者={{
_id:params.id,
}}
/>
);
}

处理此问题的最有效方法是使用Web套接字协议,该协议将从服务器向UI客户端发送通知。很难给你们举个例子,因为我们不知道你们的服务器堆栈,但像.Net世界中的SignalR这样的东西在这里是完美的

这里的前提是,与每秒向服务器请求新消息不同的是