我正在构建一个React + Mobx应用程序,我有一个情况,我有一个组件不呈现任何东西,因为它都是基于第三方地图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
}
有没有一种优雅的方式来实现这个?
如果我理解正确,你想对渲染函数中没有使用的东西作出反应。你可以这样做:
@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
shouldComponentUpdate() {
return false; // would never rerender.
}
这是我的解决方案。调用一个空函数告诉mobx你确实使用了prop。
const doNothing = () => {
// do nothing;
};
class Test extends React.component {
componentDidMount() {
mapApi.doSomething(this.props.store.value)
}
componentWillReact() {
mapApi.doSomething(this.props.store.value)
}
render () {
doNothing(this.props.store.value);
return null
}
}