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()
  }
}
相關文章
相關標籤/搜索