【问题标题】:React Native Function not returning反应本机功能不返回
【发布时间】:2016-03-09 06:29:23
【问题描述】:

我的 React Native 应用程序中有一个页面RepsPage,它根据 ID 数组呈现滚动视图。我将此数组传递给另一个函数renderRep 并尝试为数组中的每个项目返回一个视图,但返回只是空的。我试过调试它,似乎正在传递来自数据库的对象,并且肯定有要显示的内容,但它并没有成为返回函数的方式。我已经尝试过多次迭代(在 Firebase 查询中有返回函数),但似乎没有任何效果。附上代码:

export default class RepsPage extends Component {

renderRep(repID){
        var rep = new Firebase('https://ballot-app.firebaseio.com/congressPerson');       
        var nameView;
        var partyView;
        //entire function not executing? 
        rep.orderByChild("bioguideId").equalTo(repID).on("child_added", function(snapshot) {
            console.log(snapshot.val());

            nameView = <View style ={styles.tagContainer}>
                    <Text>{snapshot.val().name}</Text>
                    <Text>{snapshot.val().party}</Text>
               </View>
        });

        return (
            nameView
        );
}  

render(){ 
    var user = this.props.user;
    var reps = user.representatives;

    return (
        <ScrollView
            automaticallyAdjustContentInsets={false}
            scrollEventThrottle={200}
            style={styles.scrollView}
        >
                { reps.map(this.renderRep.bind(this)) }
        </ScrollView>
    );
}
}

【问题讨论】:

  • 显然,on("child_added",…) 是一个异步方法!你从它的回调中can't return anything。而且我很确定无论如何从render 方法中获取资源是一个非常糟糕的主意。

标签: javascript react-native


【解决方案1】:

您的 renderRep 方法应该设置状态而不是返回值。

类似的东西。请注意,我尝试编写此“盲”代码:

export default class RepsPage extends Component {
    construct() {
        this.state = {
            snapshots: []
        }
    }

    componentDidMount(){
        this.fetchRep('someid');
    }

    fetchRep(repID) {
        var rep = new Firebase('https://ballot-app.firebaseio.com/congressPerson');
        var nameView;
        var partyView;
        //entire function not executing?

        rep.orderByChild("bioguideId").equalTo(repID).on("child_added", (snapshot)=> {
            console.log(snapshot.val());
            this.setState({snapshots: [].concat(this.state.snapshots, [snapshot.val()])});
        });
    }

    renderRep() {
        return this.state.snapshots.map((snapshot)=>
            <View style={styles.tagContainer}>
                <Text>{snapshot.name}</Text>
                <Text>{snapshot.party}</Text>
            </View>
        );
    }

    render() {
        var user = this.props.user;
        var reps = user.representatives;

        return (
            <ScrollView
                automaticallyAdjustContentInsets={false}
                scrollEventThrottle={200}
                style={styles.scrollView}
            >
                { this.renderRep.bind(this) }
            </ScrollView>
        );
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-15
    • 2021-03-25
    • 1970-01-01
    • 2018-12-14
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-10-02
    • 2017-11-14
    相关资源
    最近更新 更多