首页 > 解决方案 > 从 stack-navigator-options 使用 props 调用 redux 操作

问题描述

我想从堆栈导航器选项中的 redux 调用一个操作。这是我的代码。当我使用 this.props.action_name 使用动作时,它说这不是一个函数。我在这里做错了什么?我使用navigation.params 来实现这一点,但它仍然不起作用。

componentDidMount() {
    this.props.navigation.setParams({
      referencedSharePost: this.sharePost,
      referencedDoShare: this.props.doShare
    });
  }

  sharePost = () => {
    this.props.doShare();
    console.log("DONE");
  };

  render() {
    return (
      <View style={styles.container}>
        <ScrollView>
          <WritePost profile={this.state.loggedUserProfile} />

          <View style={styles.sharePostWrapper}>
            <PostProfileBar profile={this.state.postedUserProfile} />

            <Image
              source={{
                uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
              }}
              resizeMode={"stretch"}
              style={styles.image}
            />
          </View>
        </ScrollView>
      </View>
    );
  }

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;

    return {
      headerTitle: "Share To Feed",
      headerTitleStyle: {
        paddingLeft: "20%",
        paddingRight: "20%"
      },
      headerStyle: {
        paddingRight: 10,
        paddingLeft: 10
      },
      headerLeft: (
        <Icon
          name={"close"}
          size={30}
          onPress={() => {
            navigation.goBack();
          }}
        />
      ),
      headerRight: (
        <ButtonWithoutBackground
          buttonText={styles.buttonText}
          onPress={() => params.referencedSharePost()}
        >
          Post
        </ButtonWithoutBackground>
      )
    };
  };

这就是我将状态映射到道具的方式。

import { connect } from "react-redux";
import { bindActionCreators } from "redux";

import SharePostScreen from "./SharePostScreen";
import { doShare } from "../../config/actions";

const mapStateToProps = state => {
  return {
    sharedPost: state.mainFeed.updatedPost
  };
};

const mapDispatchToProps = dispatch => {
  return {
    doShare: bindActionCreators(doShare, dispatch)
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(SharePostScreen);

我想在 stackNavigationOptions 的 onPress() 中使用 this.props.doShare。

标签: react-native

解决方案


在将其导出为默认值后,您不需要单独进行操作connect SharePostScreen,因为在组件执行期间它没有 redux 状态的实例。

因此,您可以将第二个片段中的代码移动到SharePostScreen并在那里使用它,以访问props.

const mapStateToProps = state => {
  return {
    sharedPost: state.mainFeed.updatedPost
  };
};

const mapDispatchToProps = dispatch => {
  return {
    doShare: bindActionCreators(doShare, dispatch)
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(SharePostScreen);

推荐阅读