【问题标题】:React Native - ListView not rendering data from FirebaseReact Native - ListView 不呈现来自 Firebase 的数据
【发布时间】:2016-11-19 17:41:22
【问题描述】:

我正在尝试使用 React Native ListView 组件,但它没有渲染。 ListView 采用 dataBlob 这是一个数组,这就是我要传递给它的内容。

在我的主要组件中,我使用componentWillMount 从 Firebase 获取数据。这给了我一个包含消息和发件人的对象数组。

示例:[{text: 'Hello', sender: 'p1'}, {text: 'Hi', sender: 'p2}]

主要组件:

constructor(props) {
    super(props);
    this.state = {
        messages: []
    }
}

componentWillMount() {
    app.database().ref('messages/').on('child_added', function(snapshot) {
        let data = snapshot.val();
        for(let i in data) {
            this.state.messages.push(data[i]);
        }
        this.setState({messages: this.state.messages});
    }.bind(this));
}

render() {
    return (
        <View>
            <MessagesList messages={this.state.messages}/>
        </View>
    )
}

消息列表组件:

constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2 });
    this.state = {
        dataSource: ds.cloneWithRows(props.messages)
    }
}
renderRows = (data) => {
    return (
        <View>
            <Text>{data.text}</Text>
        </View>
    )
}

render() {
    return(
        <ListView
            dataSource={this.state.dataSource}
            renderRow={(data) => this.renderRows(data)}
            enableEmptySections={true}
        />
    )
}

当我将对象数组硬编码到 dataSource 中时,它可以工作,但不适用于主组件的数组传递。

【问题讨论】:

    标签: reactjs firebase react-native firebase-realtime-database


    【解决方案1】:

    更改您的 MessagesList 组件的构造函数,例如:

     constructor(props) {
        super(props);
        this.state = {
          dataSource: new ListView.DataSource({
              rowHasChanged: (row1, row2) => row1 !== row2,
            })
        };
     }
    

    然后添加这个实用函数:

     getDataSource(messages: Array<any>): ListView.DataSource {
        if(!messages) return;
        return this.state.dataSource.cloneWithRows(messages);
     }
    

    还要加上这个:

     componentDidMount(){
        this.setState({dataSource: this.getDataSource(this.props.messages)});
     }
    

    然后这些行应该可以解决问题:

     componentWillReceiveProps(props) {
        this.setState({dataSource: this.getDataSource(props.messages)});
     }
    

    对不起,没有时间测试它,但我希望你能明白!

    【讨论】:

    • 太棒了!!!这非常有效。先生,您是我的救命恩人!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多