如何使用Mobx为FlatList设置数据?收藏页列表显示为空是什么原因?
问题原因及修复方案
- 问题1:
listData方法仅定义未执行
你在bookMarkList方法内声明了listData箭头函数,但没有触发调用,导致bookmarkApi接口请求从未发起,petList一直保持初始空数组状态,FlatList无数据可渲染。 - 问题2:请求回调
this指向丢失
就算调用listData,你给then传入的是普通函数function (responseJson),普通函数的this不指向Favorites类实例,会导致this.petList、this.userId读取报错,也无法给store的petList赋值。你之前遇到的_this2.userId报错就是this指向丢失导致的。 - 问题3:
listData未声明变量
直接写listData = () => {}没有加const/let变量声明,严格模式下会抛出全局变量赋值报错。
修复后的代码
修正后的favorites store代码
import { observable, action, makeObservable, configure } from "mobx"; import { bookmarkApi } from '../../constants/apiURL'; import AsyncStorage from '@react-native-async-storage/async-storage'; configure({ enforceActions: "never", }) class Favorites { userId = 0; petList = []; constructor() { this.bookMarkList() makeObservable(this, { userId: observable, petList: observable, bookMarkList: action, }) } bookMarkList = async () => { const value = await AsyncStorage.getItem('userId') if (value == null) return this.userId = value; // 直接发起请求,用async/await保留this指向 const res = await bookmarkApi.get('/') if (res) { this.petList = res.data.filter(data => data.userId == this.userId) } } } export const favoriteStore = new Favorites();
这里把原来的.then链式调用换成了async/await写法,逻辑更清晰,也天然保留了外层bookMarkList箭头函数的this指向,不会出现this读取undefined的问题。
FavoriteScreen.js 代码无问题
你已经用observer包裹了组件,会自动响应petList的 observable 变化,store修复后FlatList就能正常渲染数据。
内容的提问来源于stack exchange,提问作者yasin
相关产品推荐
相关产品推荐

