在redux状态的语言环境更新后重新呈现React组件

adr*_*nay 3 reactjs redux react-intl react-redux

我已经Redux在我的React应用程序中实现了,到目前为止,这工作得很好,但我有一个小问题.

我的导航栏中有一个选项可以更改locale,存储在redux's state.当我改变它时,我希望每个组件都能重新发布以改变转换.要做到这一点,我必须指定

locale: state.locale

mapStateToProps功能...这导致了很多代码重复.

有没有一种方法隐含传递现场为每个组件的道具connect与ED react-redux

提前致谢!

Ash*_*son 7

Redux实现了一个shouldComponentUpdate,它可以防止组件更新,除非它的props被更改.

在您的情况下,您可以通过传递pure=falseconnect:

connect(select, undefined, undefined, { pure: false })(NavBar);
Run Code Online (Sandbox Code Playgroud)

出于性能原因,这是一件好事,可能不是你想要的.

相反,我建议编写一个自定义连接函数,以确保locale始终添加到您的组件道具:

const localeConnect = (select, ...connectArgs) => {
  return connect((state, ownProps) => {
    return {
      ...select(state, ownProps),
      locale: state.locale
    };
  }, ...connectArgs);
};

// Simply use `localeConnect` where you would normally use `connect`
const select = (state) => ({ someState: state.someState });

localeConnect(select)(NavBar);  // props = { someState, locale }
Run Code Online (Sandbox Code Playgroud)