【问题标题】:React-Native. Can only update a mounted or mounting component反应原生。只能更新挂载或挂载组件
【发布时间】:2017-04-14 23:38:58
【问题描述】:
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>
        )
    }
}

我正在制作一个包含帖子、点赞和 cmets 的社交应用。当我想查看帖子的 cmets 时,我正在渲染一个包含所有 cmets 的列表视图。第一次尝试它有效,但如果我想查看其他帖子的 cmets,我会收到此错误。

我想我必须使用 componentWillUnmount() 但我不知道我必须在那里放什么代码。有什么想法吗?谢谢!

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    从你的构造函数中移除 this.componentDidMount() ,并移除你绑定它的那一行。它在 React 组件生命周期中被自动调用,因为你扩展了 Component 才可用。

    你还应该有 componentWillUnmount 函数,它应该调用类似的东西:

    this.commentsRef.off(...)

    为了移除监听器。为了正确地做到这一点,将 cmetsRef 回调移动到它自己的类函数(调用它 onCommentsRefValue 或其他东西),然后你可以做this.commentsRef.on('value', this.onCommentsRefValue ),随后在 componentWillUnmount 你可以调用this.commentsRef.off('value', this.onCommentsRefValue )

    【讨论】:

    • 感谢您的建议!当然会有所帮助:)
    • @rafaelqfigueiredo 我已经用更多信息更新了答案
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 2017-08-12
    • 2018-05-03
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多