javascript - 使用 Promise 时 Render 不返回任何内容

标签 javascript react-native promise render

我正在尝试实现我的渲染函数,以便它等到我完成从网络上抓取数据(如果 AsyncStorage 没有它)或从 AsyncStorage 中获取数据,但我正在努力解决 promise 方面它:

render() {
    let pic = {
        uri: 'https://i.imgur.com/G19Jnuj.jpg'
    };
    this.renderAttributes()
        .then((response) => {
            console.log("finished val: " + this.state.name);
            console.log("finished response: " + response);
            return (
                <View style={shared.basicView}>
                    <Image source={pic} style ={styles.circleImage}/>
                    <Text style={styles.infoText}>{this.state.name}</Text>
                    <Text style={styles.titleText}>Bio</Text>
                    <Text style={styles.infoText}>blah blah</Text>
                    <Text style={styles.titleText}>Email</Text>
                    <Text style={styles.infoText}>blah blah</Text>
                    <Text style={styles.titleText}
                          onPress={() => this.props.navigation.navigate('Repositories')}>
                        Public Repos Count</Text>
                    <Text style={styles.infoText}>3</Text>
                    <Text style={styles.titleText}
                          onPress={() => this.props.navigation.navigate('Followers')}>
                        Follower Count</Text>
                    <Text style={styles.infoText}>0</Text>
                    <Text style={styles.titleText}
                          onPress={() => this.props.navigation.navigate('Following')}>
                        Following Count</Text>
                    <Text style={styles.infoText}>0</Text>
                    <Text style={styles.titleText}>Profile Created</Text>
                    <Text style={styles.infoText}>November 2015</Text>
                </View>
            )
        })
        .catch((error) => {
            console.log("Profile creation failed: " + error);
            return(null);
        })
}

类的其余部分和 renderAttributes 函数的定义如下:

class ProfileScreen extends Component {
    state: any;

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            bio: '',
            email: '',
            repoCount: '',
            followerCount: '',
            followingCount: '',
            profileCreated: ''
        };
        this.renderAttributes = this.renderAttributes.bind(this);
    }

    async renderAttributes() {
        console.log("inside ga");
        let jsonData=null;
        try {
            axios.get('https://api.github.com/users/dummy')
                .then(async (response) => {
                    console.log("Response: " + JSON.stringify(response));
                    jsonData=response;
                    console.log("jsonData: " + JSON.stringify(jsonData));

                    const nameVal = await AsyncStorage.getItem('name');
                    if(nameVal !== null) {
                        console.log("name val: " + nameVal);
                        this.setState({name: nameVal});
                    }
                    else {
                        try {
                            await AsyncStorage.setItem('name', jsonData.data.name);
                        }
                        catch (error) {
                            console.log("Set name error: " + error);
                        }

                        if(jsonData.data.name == null) {
                            this.setState({name: 'n/a'});
                        }
                        else {
                            console.log("name: " + jsonData.data.name);
                            this.setState({name: jsonData.data.name});
                        }
                    }

                    const bio = await AsyncStorage.getItem('bio');
                    if(bio !== null) {
                        this.setState({bio: bio});
                    }
                    else {
                        try {
                            await AsyncStorage.setItem('bio', jsonData.data.bio);
                        }
                        catch (error) {
                            console.log(error);
                        }
                        if(jsonData.data.bio == null) {
                            this.setState({bio: 'n/a'});
                        }
                        else {
                            this.setState({bio: jsonData.data.bio});
                        }
                    }
                    // etc for each attribute in state
                })
                .catch((error) => {
                    console.log('Error fetching: ' + error);
                });

        }
        catch (error) {
            console.log('Error creating attributes: ' + error);
        }
    }

(请原谅我所有的 console.log 语句)。对我来说,无论如何,这似乎应该返回 null 或返回一个 View,但我不断收到错误 “Invariant Violation: ProfileScreen(...): Nothing was returned from render。这通常意味着返回语句丢失。或者,不渲染任何内容,返回 null。”。我的 catch 语句都没有被触发。老实说我很困惑;我注意到有两件事可能是罪魁祸首:1.我的 IDE 将 this.state.name 突出显示为未解析的变量名称,2.我没有在 renderAttributes 中显式定义 Promise (我应该这样做吗?)。另外,仅基于 print 语句,看起来 this.renderAttributes().then(response) 中的内容在 axios.get.then(); 之前打印。但不确定这是否是转移注意力。有什么建议吗?

最佳答案

其实最好的地方as stated by docs ,是 componentDidMount

您应该在第一次运行时提供一个“加载屏幕”(例如空字段和/或微调器),并在检索数据(全部在 componentDidMount 中完成)和状态集时显示它

componentWillMount:

Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.

componentDidMount:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

关于javascript - 使用 Promise 时 Render 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511326/

相关文章:

ios - CameraRoll.saveToCameraRoll() 什么都不做(iOS)

javascript - JavaScript 和 Python Promise/Awaitable Evaluation 的区别

javascript - 路径上的 d3.js 工具提示

javascript - highchart气泡图动态-json格式

react-native - 当我触摸我的文本输入时,我希望键盘根本不显示-React-Native

css - React-Native 文本不在两行

javascript - 如何让叠加层定位在图像上?

javascript - 如何使用 Grunt 丑化子文件夹/子目录中的所有 javascript 文件?

javascript promise 不传递所有参数(使用 Q)

javascript - 我违背了我的 promise