从动作计算 mobx 值

Compute mobx value from action

我目前正在重构 FreeCodeCamp 存储库作为学习 mobx 的方式。我要做的是计算 this.store.studentCount,正如您在 StudentModal 组件中看到的那样。看这里:

这是我的/client/src/components/students/Modal.js

@observer
@inject('StudentModal')
export default class StudentModal extends Component {

  store = new this.props.StudentModal()

  renderStudentCount() {
    let message
    if (this.store.studentCount > 1) {
      message = `${this.store.studentCount} students`
    } else {
      message = `${this.store.studentCount} student`
    }
    return <div id="student-count">{message}</div>
  }

  render() {
    return (
      <div className="AddStudentForm">
        <div className="class-table-button-container">
          <Button
            onClick={this.open}
          >
            Add Student
          </Button>
          {this.renderStudentCount()}
        </div>
        .....
    )
  }
}

看看我的 Modal 组件模型,您会发现我需要获取服务来获取它的长度,但出于某种原因我无法将 studentCount 设置为新值。

这是我的/client/src/models/students/Modal.js

import { observable, action } from 'mobx'
import StudentsService from '../../services/StudentsService'

export default class StudentModal {    
  @observable open = true

  @observable studentCount = 0

  @action
  fetchStudents() {
    StudentsService.fetchStudents().then(response => {
      const studentCount = response.body
      this.studentCount = studentCount.length
    })
  }
}

您可以在此处查看完整的源代码:https://github.com/imcodingideas/classroom-mode/tree/mobx-migration 我要提醒您这是开源的。

我这样做正确吗?你有什么反馈给我吗?

好像有些小事:

相同的 class 个名字

这可能会导致问题,因为您的商店和反应组件都被称为 StudentModal

装饰器顺序

正如@Joseph 建议的那样,交换您的 class:

的顺序
@inject("StudentModal")
@observer
export default class StudentModal

状态管理

 store = new this.props.StudentModal()

在创建每个 StudentModal 时,您似乎创建了一个新的状态存储。通常 te store 在你的入口点内实例化一次(除非你真的想要每个模式单独的商店)然后在以后使用:

import { render } from "react-dom";
import { Provider } from "mobx-react";
var stores = { StudentModal: new StudanModalStore() }
render(
        <Provider {...stores}>
            <StudentModal />
        </Provider>,
    rootEl,
);

@observer
@inject('StudentModal')
export default class StudentModal extends Component {
    //used getter instead of setting once
    // no longer use `new` but directly reference instance of the store. 
    get store (): StudentModalStore { return this.props.StudentModalas; }

}

以上代码是打字稿。