React Native - 使用 Firebase 的 ListView
这是我在使用 Firebase 时所做的事情,我想使用 ListView。
使用父组件从 Firebase(Posts.js) 检索数据:
Posts.js
import PostsList from './PostsList';
class Posts extends Component{
    constructor(props) {
        super(props);
        this.state = {
            posts: []
        }
    }
    
    componentWillMount() {
        firebase.database().ref('Posts/').on('value', function(data) {
            this.setState({ posts: data.val() });
        });
    }
    render() {
        return <PostsList posts={this.state.posts}/>
    }
}
PostsList.js
class PostsList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
        }
    }
    getDataSource(posts: Array<any>): ListView.DataSource {
        if(!posts) return;
        return this.state.dataSource.cloneWithRows(posts);
    }
    componentDidMount() {
        this.setState({dataSource: this.getDataSource(this.props.posts)});
    }
    componentWillReceiveProps(props) {
        this.setState({dataSource: this.getDataSource(props.posts)});
    }
    renderRow = (post) => {
        return (
            <View>
                <Text>{post.title}</Text>
                <Text>{post.content}</Text>
            </View>
        );
    }
    render() {
        return(
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                enableEmptySections={true}
            />
        );
    }
}
我想指出,在 Posts.js 中,我不是要导入 firebase,因为你只需要在项目的主要组件(你有导航器的地方)中导入一次,然后在任何地方使用它。
这是我在与 ListView 斗争时遇到的问题中有人建议的解决方案。我认为分享它会很好
资料来源:[ http://stackoverflow.com/questions/38414289/react-native-listview-not-rendering-data-from-firebase] [1 ]