如何在组件卸载时取消订阅redux store?如何装饰redux连接?

Nem*_*ree 10 javascript ecmascript-6 reactjs redux react-redux

我将以下道具(storeName)传递给我的组件:

<MyComponent reducerName="city" />
Run Code Online (Sandbox Code Playgroud)

我想用动态名称连接到商店(this.props.reducerName)

例如

export default connect(state => ({
    some: state[this.props.reducerName]
}), { })(MyComponent);
Run Code Online (Sandbox Code Playgroud)

如何装饰redux连接,或者我必须做什么?

我试图跳过redux connect并使用store.subscribe

componentDidMount() {
    store.subscribe(() => {
        this.setState({some: store.getState([this.props.reducerName]});
    });
}
Run Code Online (Sandbox Code Playgroud)

但是当我移动到另一个页面时,我看到以下错误:

警告:setState(...):只能更新已安装或安装的组件.这通常意味着您在已卸载的组件上调用了setState().这是一个无操作.

如何在组件卸载时取消订阅redux store?

kkk*_*kkk 49

要取消订阅,您可以通过以下方式简单地执行函数返回store.subscribe:

componentDidMount() {
  this.unsubscribe = store.subscribe(() => {
    // ...
  });
}
componentWillUnmount() {
  this.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

  • @flyingace我认为您误解了代码,否则我误解了您。“ store.subscribe()”返回一个新的函数,该函数将退订。我猜想store.subscribe()可能返回了一个id或具有unsubscribe方法的订阅对象,但是这种方式更为直接。 (3认同)
  • 正是这种胡言乱语让人们(有时包括我自己)声称 JavaScript 很奇怪。 (2认同)
  • 我很抱歉。我指的废话是一种必须设置一个名为“unsubscribe”的变量,其值是您希望取消订阅但在声明变量时运行的函数。我对 Redux 在订阅方法中处理取消订阅的做法持异议,而不是对你对如何完成此操作的解释(这是正确的)持异议。 (2认同)
  • 哦,现在我很好奇。在这种情况下,是否有更好的模式来处理订阅/取消订阅? (2认同)

cor*_*vid 5

connect有第二个参数ownProps,它是一个包含所有传入道具的对象。你会做这样的事情:

const mapStateToProps = (state, { reducerName = 'defaultReducer' }) => ({
  some: state[reducerName],
});

export default connect(mapStateToProps)(MyComponent);
Run Code Online (Sandbox Code Playgroud)