gpt4 book ai didi

javascript - 使用 websocket 更新 ReactJS 应用程序

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:50 24 4
gpt4 key购买 nike

我正在尝试为我的客户制作一个监督页面,但我正在努力实时更新 ReactJS 应用程序。该监控页面最多可以包含16个视频流,可以或不能同时使用。

当我使用 Django 生成页面时,我构建了一个存储在 JS 变量中的初始列表:

var anims = {{list|safe}}

我的单个视频通量的 ReactJS 代码如下:

var ModelFlux = React.createClass({
displayName : "Flux player",
propTypes: {
animID: React.PropTypes.number.isRequired,
},
componentDidMount:function() {
//generating the player
},
render: function() {
var newDivId = 'iv' + this.props.animID;
return(
React.createElement('div',{className:'col-md-3 col-sm-6 col-xs-12'},
React.createElement('div', {id:"content"},
React.createElement('div',{id:newDivId,className:'smallPl'})
)
)
)
}
})

然后,我使用以下命令生成 X 通量:

var ModelFluxwithID = anims
.map(function(anim) {return React.createElement('div',{},React.createElement(ModelFlux,{key:anim.key,animID:anim.animID}))})

最后,我调用我的应用程序:

var App = React.createClass({
displayName : "React App",
render: function() {
return(
React.createElement('div',{className:'container'},
React.createElement('div',{className:'row'},ModelFluxwithID)
)
)
}
})

ReactDOM.render(
React.createElement(App),
document.getElementById('react-app')
)

当页面生成时,它工作得很好。但我的客户不想在每次通量在线/离线时加载页面,因此我使用 websocket 实时监控每个通量的状态,从而更新动画:

ws = new WebSocket('xxxxxx');
ws.onmessage = function(event) {
// Update the anims variable
}

动画发生变化(创建/销毁)时,我如何继续更新应用程序?

最佳答案

您需要将 anim 变量保留为 App 类中的状态,并从该状态映射您的 ModelFlux 实例。然后当动画状态更新时,相关的子组件也会更新。例如,

var App = React.createClass({
displayName : "React App",
render: function() {
return(
React.createElement('div',{className:'container'},
React.createElement('div',{className:'row'},{this.mapAnims(this.state.anims)})
)
)
},
getInitialState: function() {
return {
anims: yourAnimsVariable
};
},
updateAnims: function(newAnims) {
this.setState({
anims: newAnims
});
},
mapAnims: function() {
return this.state.anims.map(function(anim) {
return React.createElement('div',{},React.createElement(ModelFlux,{key:anim.key,animID:anim.animID});
}
},
componentWillMount: function() {
var ws = new WebSocket('xxxxxx');
ws.onmessage = event => {
this.updateAnims(event.data.anims); //or wherever your new anim data is in the event
}
}
});

ReactDOM.render(
React.createElement(App),
document.getElementById('react-app')
)

关于javascript - 使用 websocket 更新 ReactJS 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40659225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com