import React, {Component} from 'react'
import {
Image,
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
ListView,
TouchableHighlight
} from 'react-native'
import ViewContainer from '../../components/ViewContainer';
import StatusbarBackground from "../../components/StatusbarBackground";
import firebase from 'firebase';
export default class Comments extends Component {
constructor(props) {
super(props)
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
comment: '',
post: '',
}
this.componentDidMount();
this.componentDidMount = this.componentDidMount(this);
this.listenForItems = this.listenForItems.bind(this);
this.renderItem = this.renderItem.bind(this);
this._comment = this._comment.bind(this);
}
componentDidMount() {
var commentsRef = firebase.database().ref('/comments')
this.listenForItems(commentsRef);
}
listenForItems(commentsRef) {
var commentsRef = firebase.database().ref('/comments')
commentsRef.on('value', snap => {
var items = [];
snap.forEach((child) => {
if(child.val().post == this.state.post){
items.push({
post: child.val().post,
email: child.val().email,
comment: child.val().comment,
uid: child.key
});
}
});
var temp = []
var len = items.length;
for (var i = (len - 1); i >= 0; i--) {
temp.push(items[i]);
}
items = temp;
this.setState({
dataSource: this.state.dataSource.cloneWithRows(items)
});
});
}
_comment(post) {
var commentRef = firebase.database().ref('/comments');
var curr = firebase.auth().currentUser.email;
var newComment = commentRef.push();
newComment.set({
'post': post,
'email': curr,
'comment': this.state.comment,
});
}
renderItem(item) {
return (
<TouchableHighlight>
<View style={styles.post}>
<Text style={styles.email}>{item.email}{' said:'}</Text>
<Text style={styles.text}>{item.comment}</Text>
<Text style={styles.line}></Text>
</View>
</TouchableHighlight>
)
}
render() {
this.state.post = this.props.post
return (
<ViewContainer>
<StatusbarBackground />
<Image style={styles.title}
source={require('../../images/comment.png')}
/>
<TextInput
style={styles.textinput}
multiline={true}
placeholder = "Write something..."
onChangeText={(comment) => this.setState({comment: comment})}
value={this.state.comment}
placeholderTextColor = 'black'
underlineColorAndroid = 'white'
autoCorrect = {false}
/>
<View style={styles.comment}>
<TouchableOpacity onPress={() => {this._comment(this.props.post)}}>
<Text>Publish</Text>
</TouchableOpacity>
</View>
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderItem} />
</View>
</ViewContainer>
)
}
}
我正在製作社交應用,包括帖子,喜歡和評論。當我想看到一篇文章的評論時,我正在渲染包含所有評論的列表視圖。第一次嘗試它的作品,但如果我想看到其他帖子的評論,我得到這個錯誤。React-Native。只能更新已安裝或安裝的組件
我想我必須使用componentWillUnmount()但是我必須在那裏放置什麼代碼。任何意識?謝謝!
謝謝你的建議!當然會幫助:) – rafaelqfigueiredo
@rafaelqfigueiredo我已經用更多的信息更新了答案 –