我正在尝试通过在react打字稿应用程序的fetch回调中更改可观察的mobx变量来更新react dom,但mobx对变量更改没有任何反应。 我这样定义变量:
@observable data:any = []
在我的构造函数中,我更改数据值:
constructor(){
this.data.push(
{
count:0,
dateTime:'2017'
})
this.getData();
}
它可以正常工作并按预期正确更新dom。
在getData()
方法中,我编写了一条提取操作以从服务器检索数据:
@action getData(){
this.data.push(
{
count:1,
dateTime:'2018'
})
fetch(request).then(response=>response.json())
.then(action((data:Array<Object>)=>{
this.data.push(data)
console.log(data)
}));
}
所以我的视图现在显示2017和2018对象数据的2值,但我从服务器获取的2019数据未显示。日志显示正确的值和以正确的方式填充的变量,但是在获取函数回调中设置任何变量后,mobx不会更新视图,我也不知道为什么? p.s:我在ECMA中也一样,没有问题,但是打字稿上的暴民行为不同
答案 0 :(得分:1)
检查我的方法:
import { action, observable, runInAction } from 'mobx'
class DataStore {
@observable data = null
@observable error = false
@observable fetchInterval = null
@observable loading = false
//*Make request to API
@action.bound
fetchInitData() {
const response = fetch('https://poloniex.com/public?command=returnTicker')
return response
}
//*Parse data from API
@action.bound
jsonData(data) {
const res = data.json()
return res
}
//*Get objects key and push it to every object
@action.bound
mapObjects(obj) {
const res = Object.keys(obj).map(key => {
let newData = obj[key]
newData.key = key
return newData
})
return res
}
//*Main bound function that wrap all fetch flow function
@action.bound
async fetchData() {
try {
runInAction(() => {
this.error = false
this.loading = true
})
const response = await this.fetchInitData()
const json = await this.jsonData(response)
const map = await this.mapObjects(json)
const run = await runInAction(() => {
this.loading = false
this.data = map
})
} catch (err) {
console.log(err)
runInAction(() => {
this.loading = false
this.error = err
})
}
}
//*Call reset of MobX state
@action.bound
resetState() {
runInAction(() => {
this.data = null
this.fetchInterval = null
this.error = false
this.loading = true
})
}
//*Call main fetch function with repeat every 5 seconds
//*when the component is mounting
@action.bound
initInterval() {
if (!this.fetchInterval) {
this.fetchData()
this.fetchInterval = setInterval(() => this.fetchData(), 5000)
}
}
//*Call reset time interval & state
//*when the component is unmounting
@action.bound
resetInterval() {
if (this.fetchInterval) {
clearTimeout(this.fetchInterval)
this.resetState()
}
}
}
const store = new DataStore()
export default store
答案 1 :(得分:0)
正如@mweststrate在评论中提到的,这是一个观察者问题,当我在我的React类的顶部添加@observer
时,该问题得到解决