mobx使用小结

62 阅读1分钟

2022-12-28

  1. 准备一个类:
export interface IListItem {
  id: string;
  value: string;
  isCompleted: boolean;
}

export class todoListStore {
  list: IListItem[] = [];

  setList(list: IListItem[]) {
    this.list = list;
  }
  
  constructor() {
    // 手动
    makeObservable(this, {
      list: observable,
      completed: computed,
      setList: action,
      addItem: action,
      changeItem: action,
      sort: action
    });
    // 自动
    // makeAutoObservable(this, {});
  }
  
  addItem(item: IListItem) {
    this.list.unshift(item);
  }

  changeItem(id: string, value?: string) {
    const index = this.list.findIndex((item) => item.id === id);
    if (value) {
      this.list[index].value = value;
    } else {
      this.list[index].isCompleted = !this.list[index].isCompleted;
    }
  }

  removeItemCompleted() {
    this.list = this.list.filter((item) => !item.isCompleted);
  }

  deleteItem(id: string) {
    const index = this.list.findIndex((item) => item.id === id);
    this.list.splice(index, 1);
  }

  sort() {
    if (!this.completed.length) {
      message.warning('无需排序');
      return;
    }
    const completedItem = this.list.filter((item) => item.isCompleted);
    const notCompletedItem = this.list.filter((item) => !item.isCompleted);
    this.list = [...completedItem, ...notCompletedItem];
  }
}

export const listStore = new todoListStore();
  1. 父组件初始化类属性值并传入组件(也可以配合useContext()来使用更简单不用一层一层传递props):
export function Parent(){
    useEffect(() => {
        listStore.setList(具体的数组);
    }, []);
    return (
        <>
            <Child store={listStore} />
        </>
    );
}
  1. 子组件接收并使用: (一定不要忘记使用mobx-react中的observer()包裹组件,否则修改数据后页面不会更新)
const TodoList = observer((props: { store: todoListStore }) => {
    const { store } = props;
    // 然后就可以正常使用了
});