React-Navigation: Use/Change header title with Redux state

女生的网名这么多〃 提交于 2021-02-18 20:11:29

问题


Is it possible to access the whole Redux state inside the React Navigation's header title?

The official docs says that the state corresponding to the navigation is accessible:

  static navigationOptions = {
    title: ({ state }) => `Chat with ${state.params.user}`
  };

But I wish to access other parts of my Redux state, with the title updating when that state updates. Is that possible today?


回答1:


this is possible with a little workaround. I would not even call this a workaround either I would call this a great feature :-)

you just have to use a new component in your header like this:

static navigationOptions = {
    header: (navigation) => {
        return <HomeViewTitle />;
    }
}

and then you can connect in my case HomeViewTitle with the redux state:

import React, { Component } from 'react';

import {
    View,
    Text
} from 'react-native';

import { connect } from 'react-redux';


class HomeViewTitle extends Component {

    render() {

        return (

            <View style={{height: 64, backgroundColor: '#000000', alignItems: 'center', justifyContent: 'center', paddingTop: 20}}>
                <Text style={{color: '#FFFFFF', fontSize: 17, fontWeight: 'bold'}}>Home</Text>
            </View>

        );

    }

}

const mapStateToProps = (state) => {
    return state;
}

export default connect(mapStateToProps)(HomeViewTitle);

then you have your redux state as props in HomeViewTitle and you can set the header dynamic




回答2:


An easier way to do this that preserves the styles of the header component is to utilize React-Navigation's getParam and setParams. In navigationOptions you would have:

static navigationOptions = ({ navigation }) => {
   return {
      title: navigation.getParam('title', 'DEFAULT VALUE IF PARAM IS NOT DEFINED'),
   };
}

and then in componentWillMount() you would have:

componentWillMount(){
   this.props.navigation.setParams({ 'title': this.props.title })
}

make sure to dispatch the title to props

const mapStateToProps = state => {
  return {
    title: state.titleSavedInState,
  }
};

The above is sufficient if you are not making any changes to the state before the state of the component (note that updating the state in redux only updates the props of the components) is updated again. However, if you are going to do be making changes while the component is open, you also need to use:

componentWillUpdate(nextProps, nextState){
    if(this.props.navigation.getParam('title', 'DEFAULT') != this.props.titleSavedInState)
    this.props.navigation.setParams({ 'title': this.props.titleSavedInState })
}


来源:https://stackoverflow.com/questions/42998253/react-navigation-use-change-header-title-with-redux-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!