所以我设置了 mobx 并且文件在 Visual Studio 代码中没有显示错误,并且反应客户端应用程序编译得很好,它显示了部门列表,但还有一个按钮无法正常工作,它的设置一切正常,onClick事件一切正常,但它不起作用我在使用 mobx 时遇到问题,因为它大于版本 6 或 idk 其版本,所以我不得不添加构造函数来显示列表
百货公司
import {observable, action, makeObservable} from 'mobx';
import { createContext } from 'react';
import agent from '../api/agent';
import { IDepartment } from '../models/department';
class DepartmentStore {
@observable departments: IDepartment[] = [];
@observable selectedDepartment: IDepartment | undefined;
@observable loadingInitial = false;
@observable editMode =false;
constructor() {
// Just call it here
makeObservable(this);
}
@action loadDepartments= () => {
this.loadingInitial = true;
agent.Departments.list()
.then(departments => {
departments.forEach((department) => {
this.departments.push(department);
})
}).finally(() => this.loadingInitial = false);
};
@action selectDepartment = (id: string) => {
this.selectedDepartment = this.departments.find(d => d.id === id);
this.editMode = false;
}
}
export default createContext(new DepartmentStore());
所以这里的所有内容都没有显示错误,下面会显示 DepartmentList 代码,其中包含现在正在运行的按钮
import { observer } from "mobx-react-lite";
import React, { SyntheticEvent, useContext } from "react";
import { Item, Button, Segment } from "semantic-ui-react";
import { IDepartment } from "../../../app/models/department";
import DepartmentStore from "../../../app/stores/departmentStore";
interface IProps {
deleteDepartment: (event: SyntheticEvent<HTMLButtonElement>,id: string) => void;
submitting: boolean;
target: string;
}
export const DepartmentList: React.FC<IProps> = ({
deleteDepartment,
submitting,
target
}) => {
const departmentStore = useContext(DepartmentStore);
const {departments, selectDepartment} = departmentStore;
return (
<Segment clearing>
<Item.Group divided>
{departments.map((department) => (
<Item key={department.id}>
<Item.Content style={{ display: "flex" }}>
<Item.Header style={{ width: "100%", marginTop: "1em" }}>
{department.name}
</Item.Header>
<Item.Extra>
<Button
name={department.id}
loading={target === department.id && submitting}
onClick={(e) => deleteDepartment(e, department.id)}
content="Delete"
color="red"
floated="right"
/>
<Button
onClick={() => selectDepartment(department.id)}
content="View"
color="blue"
floated="right"
/>
</Item.Extra>
</Item.Content>
</Item>
))}
</Item.Group>
</Segment>
);
};
export default observer(DepartmentList)
;