【问题标题】:react mobx, component does not render new observable反应 mobx,组件不呈现新的 observable
【发布时间】:2018-12-03 10:33:58
【问题描述】:

我正在使用 Mobx 和 React (typescript) 从 firebase 获取一些数据并显示它。在第一次渲染时,屏幕上不会渲染任何数据,直到我更改例如选项卡以重新渲染组件。

  • 组件类:

    interface Props {id: string; mytore?: MyStore;}
    @inject('mystore')
    @observer
    export class myClass extends Component<Props>{
      constructor(props: Props) {super(props);}
      componentDidMount() {   this.props.mystore!.getBs(this.props.id);}
      render() {
         const { arrB } = this.props.mystore!;
         return (
            <div>{arrB.map((e) => (<h3 key={`${e.id}`}>{e.name}</h3>))}</div>
            );
         }
    }
    
  • 商店类

    export class MyStore{
    @observable arrA=[];
    @observable arrB=[];
    
    constructor(){this.loadAllAs()}
    
    @action.bound loadAllAs(){runInAction(async()=>(this.arrA=await /*fetchfunction*/))}
    
    @action getBs(id){this.arrB=arrA.filter(/*some logic*/)}
    }
    

    所以这里 arrB 在调用该方法后被操纵,它是一个可观察的,它在组件的渲染方法中得到解构,所以我期待对 arrB 的任何更改都会导致重新渲染但没有任何反应直到关于其他操作 componentDidMount 被调用。

【问题讨论】:

    标签: reactjs mobx-react mobx-state-tree


    【解决方案1】:

    因为 arrB 必须是 @computed computed

    @computed
    getBs(id){
       return this.arrA.filter(/*some logic*/)}
    }
    
    const { getBs } = this.props.mystore!;
    
    getBs(id).map...

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2017-05-12
      • 2017-08-24
      • 2018-07-28
      相关资源
      最近更新 更多