mobx使用跳坑

mobx确实很好用,但坑也是迷之多,这里仅记下使用时遇到的小坑javascript

1 mobx + react-router4 不跳转

解决方案:须要在写路由跳转的容器App.js和有跳转的容器A.js, B.js中添加@withRouterjava

参考资料:https://github.com/mobxjs/mobx-react/issues/274react

App.jsgit

import React from 'react'
import { Switch, withRouter } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import routes, { RouteWithSubRoutes } from './routes'

@inject('commonStore')
@withRouter
@observer
class App extends React.Component {
......
  render () {
    return (
        <Switch>
          {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
        </Switch>
      )
  }
}

 

A.jsgithub

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react'
import { withRouter } from 'react-router-dom'

const Item = List.Item;

@inject('walletStore', 'commonStore')
@withRouter
@observer
class APage extends Component {
  handleClick = url => {
    this.props.history.push(url)
  }
......
}

 

 

2 @action中this提示‘undefined’

解决方案:调用action的时候须要使store.actionreact-router

错误代码dom

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react'
import { withRouter } from 'react-router-dom'


@inject('articleStore')
@withRouter
@observer
class Article extends Component {
 
  componentDidMount () {
    const { articleStore } = this.props
    const { getIntegralTotalScore } = articleStore
    getIntegralTotalScore()
  }
}

 

正确代码this

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react'
import { withRouter } from 'react-router-dom'


@inject('articleStore')
@withRouter
@observer
class Article extends Component {
 
  componentDidMount () {
    const { articleStore } = this.props
    articleStore.getIntegralTotalScore()
  }
}
相关文章
相关标签/搜索