如何仅在 React 属性 更改时调用函数?

How do I call a function only when a React property changes?

我希望在每次 Meteor 订阅时显示一个模态对话框(例如 alert()),在 React 中跟踪 withTracker,更改。

我曾尝试使用 Tracker.autorun 来跟踪更改,但无法确定在代码中放置它的位置。它似乎在 Component 构造函数中不起作用,如果放在 render().

中,它每次都会运行

这是我的代码的概要:

class Foo extends Component {
    render() {
        return (
            <h1>Example Header</h1>
            { this.maybeShowAlert() }
        );
    }

    maybeShowAlert() {
       // ONLY if bar has been updated
       alert('bar has changed');
    }
}

export default withTracker(() => {

    Meteor.subscribe('bar')

    return {
        bar: Bar.findOne({})
    };
})(Foo);


之前没有使用过 Meteor,但如果您想响应 state/prop 更改,那么 componentDidUpdate() 是它的生命周期方法。例如

componentDidUpdate(prevProps) {
    if (this.props.bar !== prevProps.bar {
        // bar prop has changed
        alert("bar changed);
    }
}

如果您要使用 Tracker.autorun,那么最好在 componentDidMount 中调用它,因为它只在组件 mounted. You only need to call the tracker function once since the tracker function will rerun whenever the reactive data sources that it depends on ever changes 之后调用一次。在跟踪器函数中,您将根据 bar 的值调用 maybeShowAlert,就像这样,

componentDidMount() {
    Tracker.autorun(() => {
        let bar = this.props.bar;
        if (bar) {
            this.maybeShowAlert();
        }
    }
}