【发布时间】:2017-06-01 03:57:34
【问题描述】:
问题
如何在每次服务器更新时更新我的文本/图像。
我希望发生的事情
- 服务器向 DB 添加文本
- 使用 Web 套接字的服务器消息 RN 应用
- RN 应用向服务器请求数据
- 服务器向 DB 请求数据
- 服务器向 RN 应用发送数据
- RN 应用使用新数据更新
<ScrollView>
发生了什么
- 服务器向 DB 添加文本
- 使用 Web 套接字的服务器消息 RN 应用
- RN 应用向服务器请求数据
- 服务器向 DB 请求数据
- 服务器向 RN 应用发送数据
注意:我知道服务器将正确的数据发送到 RN 应用程序并且应用程序接收到数据。我已经console.loged 了。
数据
这是从服务器发送到 RN 应用程序的数据示例:
[ { _id: 592f7a5c74376a749e2db211,
name: 'world',
allowedUsers: [ '114135152003891444692', '114135152003891444692' ],
firstUser: '114135152003891444692',
imageSrcList:
[ 'hello world',
'hello moon',
'',
'images/WedMay31201720:38:57GMT-0700(PDT)MILI1496288337083myUserName.jpg' ] },
{ _id: 592f8bf462d68f777dd47cfb,
name: 'hello',
allowedUsers: [ '114135152003891444692', '114135152003891444692' ],
firstUser: '114135152003891444692',
imageSrcList:
[ 'foo',
'bar',
'',
'images/WedMay31201720:39:01GMT-0700(PDT)MILI1496288341061myUserName.jpg' ] } ]
它由一组对象组成。
每个对象包括:
-
_id唯一的标识符 -
name个人名字,可以重复 -
allowedUsers和允许的用户数组 -
firstUser第一个用户 - 以及启动“池”的用户 -
imageSrcList这包括图像和聊天的 URL 消息,这是我需要帮助的地方。
我希望应用如何解释数据。
每个“池”都是上述数组中的一个对象。当用户单击“池”时,我想让应用显示所有“聊天”文本以及来自imageSrcList 的图像。
应该怎么做
(在我看来 - 如果你知道更好的方法,一定要分享!)
- 对数组进行排序以找到正确的“池”
- 对
imageSrcList的每个元素进行排序,找出哪些是照片,哪些是聊天消息。 - 添加必要的 JSX 代码(例如
<Text>或<Image/>) - 推送到输出数组
- 在
<ScrollView>中显示输出数组
当前解决方案
此解决方案不起作用,但它应该可以帮助您了解我想要做什么。
loadData(cb) {
fetch('http://localhost:8000/home/' + this.state.user.id)
.then((response) => response.json())
.then((responseText) => {
console.log('done laoding inicial data: ');
console.log(responseText.pools);
console.log(this.props.navigation.state.params._id);
cb(responseText.pools)
})
.catch((error) => {
this.setState({ myValues: error, loaded: true, });
});
}
...和
ws.onmessage = (e) => {
console.log('MESSAGE');
this.loadData(function(listObj){
for (var i = 0; i < list.length; i++) {
if (listObj[i]._id === params._id){
params.list = listObj[i].imageSrcList;
console.log(listObj[i].imageSrcList);
}
}
list = params.list;
output = [];
for (var i = 0; i < list.length; i++) {
if ( (typeof list[i] === 'string') && (list[i].includes('.jpg')) ){
output.push(<Image
style={styles.preview}
source={{uri: 'http://localhost:8000/' + list[i] }}
/>);
}else if( typeof list[i] === null ){
output.push();
}else if ( list[i] === ''){
output.push()
}else{
output.push(<Text>{list[i]}</Text>);
}
}
});
};
...和
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.scrollView.scrollToEnd({animated: true});
}}>{output}</ScrollView>
更多信息
- 我正在使用 React Native
- 我用的是IOS
- 我正在使用 NodeJS/Express 作为服务器
【问题讨论】:
标签: ios node.js react-native websocket fetch