0

我正在构建一个 React + Mobx 应用程序,我有一个组件不渲染任何内容,因为它全部基于 3rd 方地图 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
}

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

4

2 回答 2

1

如果我对您的理解正确,您想对渲染功能中未使用的内容做出反应。你可以这样做:

@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

于 2017-05-22T12:35:22.110 回答
0

你可以使用shouldComponentUpdate

shouldComponentUpdate() {
  return false; // would never rerender.
}
于 2017-05-22T11:57:38.050 回答