有没有不调用 setParams (react-navigation) 的 re-render 导航栏?

Is there anyway to re-render navation bar without calling setParams (react-navigation)?

我正在为我的应用实现 multi-language 功能,但我在更改 React 导航 header 标题(使用 react-navigation)时卡住了。我不想在每个屏幕上调用 setParams 来根据 selected 语言更改 header 标题。

这是我的堆栈:

Home -> Settings -> App Settings -> Language Settings.

我在 Language Setting 屏幕上使用 select 语言。按导航栏上的默认后退按钮返回后,调用 App Settings 屏幕中的 static navigationOptions(这是我根据当前语言设置标题的地方),即使我不调用 setParams(),我不知道为什么不是 re-rendered => header title doesn't change.

有什么办法可以解决这个问题吗?


嗨@JavaEvgan 这是我的代码:

    <AppNavigator navigation={addNavigationHelpers({
      dispatch: this.props.dispatch,
      state: this.props.navigationState
    })}/>

连接到 redux 存储

export default connect(state => ({
  navigationState: state.navigationState,
}), dispatch => ({
  dispatch: dispatch
}))(MainLayoutContainer)

刚刚从原始文档中找到了适合您的解决方案,而且非常简单。您只需为不同的语言版本和一个父组件创建两个(或更多)导航组件。在父组件中,您需要根据您的状态使用 "Conditional rendering"(if 语句)和 return 正确的导航。查看条件渲染的原始文档:

ReactJS docs - Conditional rendering

来自文档:

Consider these two components:

function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}

We'll create a Greeting component that displays either of these components depending on whether a user is logged in:

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
  return <UserGreeting />;
}
  return <GuestGreeting />;
}

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

Try it on CodePen.

This example renders a different greeting depending on the value of isLoggedIn in prop

我找到了解决方案,使用 screenProps 将额外信息传递给 children https://reactnavigation.org/docs/navigators/stack#Navigator-Props

    <AppNavigator
      screenProps={this.props.settings}
      navigation={addNavigationHelpers({
      dispatch: this.props.dispatch,
      state: this.props.navigationState
    })}/>

并将其连接到 redux store

export default connect(state => ({
  settings: state.settings,
  navigationState: state.navigationState,
}), dispatch => ({
  dispatch: dispatch
}))(MainLayoutContainer)

像这样,static navigationOptions 每次商店设置更改时都会收到电话 re-render