javascript - 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>
</>
);
}
}
解决方案
将方法传递给 onDidFocus 时需要删除括号。让它看起来像这样:onDidFocus={this.getFreelancerList}
这是 react 的常见问题。当你在函数名后面加上括号时,你实际上是在执行函数。根据您的代码,看起来这实际上不是您的意图。您正在尝试将回调传递给 onDidFocus,以便当且仅当组件接收到焦点时,才会调用该方法。
您遇到无限循环的原因是您正在更新 getFreelancerList 中的状态。所以你的组件渲染了,你立即调用getFreelancerList
. 在getFreelancerList
中,您正在更新状态,导致组件再次呈现。然后,你猜对了,当组件重新渲染时,它getFreelancerList
再次调用,循环重复:)
推荐阅读
- git - 更新被拒绝,因为遥控器包含您提示的工作:本地没有.. git 推送到 heroku 时出错
- remote-access - 将文件从服务器发送到通过 VPN 连接的客户端
- python - Python Typing:根据函数参数声明返回值类型
- php - 检查某列是否有重复值
- android - 设置通用链接 - 可以 .well-known 在子目录而不是根目录下
- shell - 在 shell 脚本中使用 lockf 实用程序实现互斥操作的正确方法
- java - 获取 Threaddump java.lang.Thread.State: BLOCKED (on object monitor) at org.hsqldb.Session.setAutoCommit(Unknown Source)
- flutter - 扑动的AppBar
- mysql - mysql 5.4 版的链表数据中的序列
- flutter - Flutter StreamBuilder 与 Firestore 分页