如何在不使用 mobx 渲染的情况下对道具更改做出反应

How to react to a prop change without render it using mobx

我正在构建一个 React + Mobx 应用程序,我有一个组件不渲染任何东西,因为它全部基于第 3 方地图 API,但我需要对一些商店 属性 变化:

componentDidMount() {
   mapApi.doSomething(this.props.store.value)
}

componentWillReact() {
   mapApi.doSomething(this.props.store.value)
}

render () {
   //workaround to make componentWillReact trigger
   console.log(this.props.store.value) 
   return null
}

有没有一种优雅的方式来实现这个?

您可以使用 shouldComponentUpdate

shouldComponentUpdate() {
  return false; // would never rerender.
}

如果我没理解错的话,你想对渲染函数中没有使用的东西做出反应。你可以这样做:

@observer 
class ListView extends React.Component {
   constructor(props) {
      super(props)
   }

@observable filterType = 'all'

handleFilterTypeChange(filterType) {
  fetch('http://endpoint/according/to/filtertype')
    .then()
    .then()
}

  // I want the method that autoruns whenever the @observable filterType value changes
 hookThatDetectsWhenObservableValueChanges = reaction(
    () => this.filterType,
    filterType => {
      this.handleFilterTypeChange(filterType);
    }
 )
} 

这里提到了这个解决方案https://github.com/mobxjs/mobx-react/issues/122#issuecomment-246358153