Mobx反应永远不会更新

时间:2017-06-21 01:26:13

标签: javascript reactjs mobx mobx-react

我正在尝试理解React中的mobx实现。我使用create react app并更新默认配置以使用装饰器。然后我创建了一个这样的简单商店:

编辑:在Ben Hare之后(感谢他!)回复我更新了我的代码:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import MessageStore from "./store/messages";

ReactDOM.render(<App store={new MessageStore()} />, 
document.getElementById('root'));

** App.js **

import React from "react";
import { observer } from "mobx-react";

@observer
export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.store = props.store;
    }

    render() {
        return <ul>
            { this.store.allMessages.map((msg) => {
                return <li key={msg}>{msg}</li>
            })}
        </ul>
    }
}

messages.js

import {action, observable, computed} from "../../node_modules/mobx/lib/mobx";

export default class MessageStore {

    @observable messages = ["My first message"];

    constructor() {
        setInterval(() => {
            // Add some random messages every second
            this.addMessage(Math.random());
        }, 1000);
    }

    @action addMessage(msg) {
        this.messages.push(msg);
    }

    @computed get allMessages() {
        return this.messages;
    }

}

显示第一条消息,但是当setInterval将消息添加到商店时,组件永远不会更新。你能救我吗?

2 个答案:

答案 0 :(得分:0)

适合我:

https://codesandbox.io/s/LgQXNBnNW

您是否在浏览器日志或终端中看到任何错误?

答案 1 :(得分:0)

请检查我的方法。也许会有所帮助: MobX商店:

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