mobx结合useContext没有触发更新

2021-10-18  本文已影响0人  CRJ997
// mobx home store
import {  observable, action } from 'mobx;

class Home {
  @observable
  public a = 'button';
  
  @action
  setA =  (a: string) => {
    this.a = a;
  };
}

export default new Home();
import React from 'react';
// context.ts
import homeStore from './homeStore';
export default homeContext = React.createContext({
  homeStore
});
// componentA
import React from 'react';
import homeContext from './homeContext'

export default function ComponentA (props) {
  const { a, setA } = useContext(homeContext);

  return (
    <button onClick={() => { setA('NICE') }}>{a}</button>
  );
}

点了之后按钮文字没有变化

解决方案用mobx-react的inject和observer去装饰function component。

上一篇下一篇

猜你喜欢

热点阅读