关于Mobx inject传值问题?

按照文档正常配置了Mobx,在子组件中想通过inject的形式获取和调用参数,但是出现了undefined问题?

// index.ts
ReactDOM.render(
    <Provider timerStore={TimerStore}>
        <div>
            <App/>
            <DevTools />
        </div>
    </Provider>,
    document.getElementById('root') as HTMLElement
);
// App.ts
interface IProps {
  timerStore?: TimerStore;
}

interface IState {
    timer: number;
}

@inject('timerStore')
@observer
class App extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);

    const { timer } = this.props.timerStore as TimerStore;
    console.log(timer);
    
        this.state = {
            timer
        };
  }

    public render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                </header>
                <p className="App-intro">
                    To get started, edit <code>src/App.tsx</code> and save to reload.
                </p>
                <Main name="hello wrold" />
        <Timer/>
                <TimerLess timer={this.state.timer} />
            </div>
        );
    }
}

export default App;
// TimerStore.ts
import { observable, action } from "mobx";

export class TimerStore {
  @observable public timer = 1;

  @action.bound
  public add() {
    this.timer += this.timer;
  }

  @action.bound
  public reset() {
    this.timer = 0;
  }
}

export default new TimerStore();
// Timer.ts
interface IProps {
  timerStore?: TimerStore;
}

interface State {}

inject('timerStore')
@observer
export default class Timer extends React.Component<IProps, State> {
  constructor(props: IProps) {
    super(props);
    this.state = {};

    this.onClickBtn = this.onClickBtn.bind(this)
  }

  public onClickBtn():void {
    const tStore = this.props.timerStore as TimerStore;
    console.log(tStore);   // undefined
  }

  public render() {
    const tStore = this.props.timerStore as TimerStore;
    console.log(tStore); // undefined

    return (
      <div onClick={this.onClickBtn}>Seconds passed: {1}</div>
    )
  }
}

App.ts中,我们可以正常的获取数据,但是在子组件Timer.ts,通过inject的方式注入store时,获取相应的store,会是undefined,查了好多原因,都不知道问题出了哪里??求搭建帮忙解决一下?

阅读 9.1k
4 个回答
新手上路,请多包涵

这个问题我答不上来,想另外请教一下题主关于注入时ts报错的问题
如下图 我若是在interface里声明 并配置可选属性 那么就会出现下图这种报错, 但我若是不配置可选只是声明,父组件就会报错说我没传wallData这个props让我给他props,但是这个本来就不是父组件传的啊。。。。
clipboard.png
clipboard.png

babel配置文件需要安装‘babel-plugin-transform-decorators-legacy’、'babel-preset-stage-1',两款插件
可能是由于修饰器@dec是es7最新语法 需要解析

新手上路,请多包涵

试下Provider的下一层div添加属性timerStore={TimerStore}, 我是这样能行的,感觉这样就变成了父子组件传输

新手上路,请多包涵

你的子组件Timer.ts 里面的inject少了个@符号吧!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题