可观察的阵列不会重新呈现组件

时间:2019-06-15 15:14:39

标签: javascript reactjs mobx mobx-react

我有很多商店,在其中一个商店中进行更改不会改变组件的状态,直到更改组件的状态。

我认为那是我使用了错误的观察者,但是相同的代码在另一家商店也可以使用。

商店的代码:

import invariant from 'invariant'
import { action, computed, observable } from 'mobx'
import { postData } from '../utils/api-helpers'
import {
  ActionStatus,
  IConfigurationStore,
  ITag,
  ITagsStore,
  IUserStore,
  TagType
} from '@@types'

export class Tag implements ITag {
  @observable
  public id: string
  @observable
  public tag: string

  constructor(tag: TagType) {
    this.id = tag.id
    this.tag = tag.tag
  }
}


export class TagsStore {
  public readonly storeName: string = 'Tag'
  public configuration: IConfigurationStore | null = null

  @observable public items: ITag[] = []

  private storage: Storage | null = null

  @action
  public setConfiguration = async (configuration: IConfigurationStore): Promise<void> => {
    invariant(!!configuration.config, 'КConfiguration wasnt initialized correctly')
    this.configuration = configuration
    this.storage = new Storage(this.configuration!.config!)
    await this.fetchAll()
  }

  @action
  private fetchAll = async () => {
    const response = await postData(
      this.configuration!.createBackendUrl('/tags', this.configuration!.config!.ENDPOINTS.API!),
      {
        method: 'GET',
        phone: (this.configuration!.stores.user as IUserStore).credentials.phone,
        token: (this.configuration!.stores.user as IUserStore).token,
      }
    )

    if (response.data.code === 409) {
      ;(this.configuration!.stores.user as IUserStore).logout()
    } else {
      response.data.data.attributes.tags.forEach((tag: TagType) => {
        this.items.push(new Tag(tag))
      })
    }
  }
}

和组件:

import { withStyles } from '@material-ui/core'
import { inject, observer } from 'mobx-react'
import React from 'react'
import uuid from 'uuid'


const styles: any = {
  actions: {
    bottom: '0',
    position: 'absolute',
    width: '100%',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    width: '100%',
  },
  inputRow: {
    marginLeft: '20px',
  },
}

inject('tags', 'dumkas', 'errors', 'configuration')
@observer
export class NewDumka extends React.Component<Props, State> {
  public state: State = {
    form: { ... },
  }

  private inputs: string[]

  constructor(props: Props) {
    super(props)

    this.inputs = [uuid.v4(), uuid.v4(), uuid.v4()]
    this.props.dumkas!.newDumka().then(newDumka => {
      this.state = {
        form: { ... },
      }
    })
  }


  public render() {
    const { classes, tags } = this.props
    return (
      tags!.items.map(tag => tag.title}
    )
  }
}

export default withStyles(styles)(NewDumka)

只有状态会改变形式时,才会呈现道具。

道具没有在componentWillReceiveProps中被拦截。

0 个答案:

没有答案