如何在 React Native Mobx 中设置数组值?
How to set array value in react native mobx?
我有 favoriteStore,我是 mobx 的新手,我想将数组从 bookmarkapi 设置为 petList 数组,但我遇到了错误。
错误;
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_this2.userId')]
代码;
import { observable, computed, action, makeObservable, configure } from "mobx";
import { bookmarkApi, petApi } from '../../constants/apiURL';
import AsyncStorage from '@react-native-async-storage/async-storage';
configure({
enforceActions: "never",
})
class Favorites {
userId = 0;
petList = [];
constructor() {
makeObservable(this, {
userId: observable,
petList: observable,
bookMarkList: action
})
}
bookMarkList = async () => {
const value = await AsyncStorage.getItem('userId')
if (value != null) {
this.userId = value;
console.log(this.userId);
}
bookmarkApi.get('/').then(function (responseJson) {
this.petList = responseJson.data.filter(data => data.userId == this.userId)
})
}
}
export const favoriteStore = new Favorites();
回调函数丢失上下文,bookmarkApi.get
回调只使用箭头函数。
我有 favoriteStore,我是 mobx 的新手,我想将数组从 bookmarkapi 设置为 petList 数组,但我遇到了错误。
错误;
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_this2.userId')]
代码;
import { observable, computed, action, makeObservable, configure } from "mobx";
import { bookmarkApi, petApi } from '../../constants/apiURL';
import AsyncStorage from '@react-native-async-storage/async-storage';
configure({
enforceActions: "never",
})
class Favorites {
userId = 0;
petList = [];
constructor() {
makeObservable(this, {
userId: observable,
petList: observable,
bookMarkList: action
})
}
bookMarkList = async () => {
const value = await AsyncStorage.getItem('userId')
if (value != null) {
this.userId = value;
console.log(this.userId);
}
bookmarkApi.get('/').then(function (responseJson) {
this.petList = responseJson.data.filter(data => data.userId == this.userId)
})
}
}
export const favoriteStore = new Favorites();
回调函数丢失上下文,bookmarkApi.get
回调只使用箭头函数。