gpt4 book ai didi

javascript - 在 redux Action 创建者中设置监听器是一个坏主意吗?

转载 作者:行者123 更新时间:2023-12-01 03:27:29 26 4
gpt4 key购买 nike

我正在构建一个应用程序,它会不断监听位置变化并更新商店。我想知道将监听器放置在 Action 创建器中而不是组件本身是否是一个好主意。

例如,

componentWillMount() {
this.props.watchLocation();
}

// inside action creator
export function watchLocation() {
LocationManager.on("location", location => {
dispatchLocationlocation);
});
}

或者相反,在我的 react native 组件内,

componentWillMount() {
LocationManager.on("location", location => {
// call action to dispatch location updates
});
}

如果我将听众置于 Action 创建者中,性能方面会有什么差异?

最佳答案

就性能而言,我认为这没有太大区别,但我不同意 Varun 关于听众位置的回答。如果您创建这样的操作并分派(dispatch)一次,则需要一个额外的操作来更新存储(当然,您可以使用 thunk 来实现),并且以后可能很难禁用回调,因为您无法访问回调引用,因为它仅在操作调用中使用。如果您使用 componentDidMount/componentWillUnmount 生命周期方法来跟踪事件处理程序,则很容易避免内存泄漏。顺便说一下,不要将 componentWillMount 用于任何可能导致副作用的事情:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

请参阅documentation了解更多信息。

关于javascript - 在 redux Action 创建者中设置监听器是一个坏主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com