首页 > 解决方案 > React Native NavigationEvents:onDidFocus 获得无限循环

问题描述

我正在使用NavigationEvents自动加载我的列表。

到目前为止,它确实有效,它加载了我更新的列表,但在控制台上它继续在 INFINITE LOOP 上运行 API 调用函数。

但是,每当我打开列表屏幕时,我只想加载一次 API 调用函数。

因此,如果有更好的解决方案,请随时提供帮助。

下面的代码片段:

import { NavigationEvents } from 'react-navigation';

import NameActionBar from '../components/mNameActionBar';
import FreelancerList from '../components/mFreelancerList';

export default class MasterScreen extends Component {

    componentDidMount() {
        this.getFreelancerList();
        console.log('ComponentDidMount()');
    }

    getFreelancerList() {
        console.log('Freelancer List');
        let self = this;
        AsyncStorage.getItem('my_token').then((keyValue) => {
            console.log('Master Screen (keyValue): ', keyValue); //Display key value
            axios({
                method: 'get',
                url: Constants.API_URL + 'user_m/freelancer_list/',
                responseType: 'json',
                headers: {
                    'X-API-KEY': Constants.API_KEY,
                    'Authorization': keyValue,
                },
            })
                .then(function (response) {
                    //console.log('Response Data: ', response.data.data);
                    console.log('Response: ', response);
                    self.setState({
                        dataSource: response.data.data,
                    });
                })
                .catch(function (error) {
                    console.log('Error: ', error);
                });
        }, (error) => {
            console.log('error error!', error) //Display error
        });
    }

    viewFreelancerList() {
        const { dataSource } = this.state;
        return (
            <View>
                <FlatList
                    data={dataSource}
                    keyExtractor={({ id }, index) => index.toString()}
                    renderItem={({ item }) => <FreelancerList {...item} />}
                />
            </View>
        );
    }

    render() {
        return (
            <>
                {<NavigationEvents onDidFocus={this.getFreelancerList()} />}
                <NameActionBar />
                <ScrollView>
                    {this.viewFreelancerList()}
                </ScrollView>
            </>
        );
    }
}

标签: javascriptreact-nativereact-navigation

解决方案


将方法传递给 onDidFocus 时需要删除括号。让它看起来像这样:onDidFocus={this.getFreelancerList}

这是 react 的常见问题。当你在函数名后面加上括号时,你实际上是在执行函数。根据您的代码,看起来这实际上不是您的意图。您正在尝试将回调传递给 onDidFocus,以便当且仅当组件接收到焦点时,才会调用该方法。

您遇到无限循环的原因是您正在更新 getFreelancerList 中的状态。所以你的组件渲染了,你立即调用getFreelancerList. 在getFreelancerList中,您正在更新状态,导致组件再次呈现。然后,你猜对了,当组件重新渲染时,它getFreelancerList再次调用,循环重复:)


推荐阅读