【问题标题】:React MOBX Component RenderReact MOBX 组件渲染
【发布时间】:2018-07-24 20:37:20
【问题描述】:

我刚刚切换了 this.setState 以使用 mobx observable,因为我有多个获取数据的 GET 请求。这可以防止每次调用 this.setState 时重新渲染 PieChart

但是,现在子组件永远不会重新渲染,而是使用初始占位符 mobxState。当 PieChart 子组件的数据来自 API 时,如何让其重新呈现。

class Device extends React.Component {
  mobxState = {
    customOptions: [],
    rowData: []
  };

  //mount data
  componentDidMount() {
    //call the data loader
    this.fetchData();
  }

  fetchData = () => {
    axios
      .get("/custom_options.json")
      .then(response => {
        this.mobxState.customOptions = response.data.custom_options;
      })
      .then(
        //data for PieChart, need this portion to render the PieChart
        axios.get("/devices.json").then(response => {
          this.mobxState.rowData = response;
        })
      );
  };

  render() {
    return <PieChart data={this.mobxState.rowData} />;
  }
}

decorate(Device, {
  mobxState: observable
});

export default Device;

【问题讨论】:

    标签: javascript reactjs mobx mobx-react


    【解决方案1】:

    您需要确保您的Device 组件是observer,如果您使用的是低于5 的MobX 版本,您必须在render 方法中slice() or peek() 数组。

    import { observer } from "mobx-react";
    
    class Device extends React.Component {
      // ...
    
      render() {
        return <PieChart data={this.mobxState.rowData.slice()} />;
      }
    }
    
    decorate(Device, {
      mobxState: observable
    });
    
    export default observer(Device);
    

    【讨论】:

    • 我使用的是 mobx 5.0.3。如果我尝试使用 .peek() 它会出错:this.mobxState.rowData.peek is not a function
    • 使用observer(Device) 会产生ReferenceError: observer is not defined
    • @HoosierCoder 当然要先导入。
    • 我的导入语句是:import { decorate, observable, computed, action } from "mobx"
    • observable 被导入,但不是 observer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2020-01-31
    • 2018-01-28
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多