gpt4 book ai didi

javascript - react native 导航事件 : onDidFocus getting Infinite Loop

转载 作者:行者123 更新时间:2023-12-01 23:07:49 25 4
gpt4 key购买 nike

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

到目前为止,它确实有效并加载了我的更新列表,但在控制台上它一直在无限循环上运行 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>
</>
);
}
}

最佳答案

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

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

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

关于javascript - react native 导航事件 : onDidFocus getting Infinite Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com