【问题标题】:React Navigation losing props that are passed downReact Navigation 丢失了传递下来的道具
【发布时间】:2018-06-20 00:23:47
【问题描述】:

由于connect(mapStateToProps, mapDispatchToProps) 行,我有一个连接到redux 的容器,它继承了“全局状态”作为道具...

容器(Container.js) 反过来将道具传递到表(Table.js),它按预期接收它们。

当我尝试将表格设置为导航堆栈时,会出现我的问题。原因是我希望能够单击将导航到 DetailPage 的每一行,该 DetailPage 将由依赖于行的不同道具填充。

但是,当添加 StackNavigator 时,我从 Container 传递的所有道具都消失了,只有 React Navigation 存在 (navigation: {actions:{goBack... ETC}})。

注意:如果我直接connect 组件也会发生这种情况。

以下是我的代码结构的简化示例。

我做错了什么/如何维护传承下来的道具?

容器.js

class Container extends Component {
  render() {
    return (
      <View>
        <Table {...this.props} />
      </View>
    )
  }
}


const mapStateToProps = state => {
  return {
    data: state.data,
    propTwo: state.propTwo
  }
}

const mapDispatchToProps = dispatch => {
  return {
    functionOne: () => dispatch(functionOne()),
    functionTwo: arg => dispatch(functionTwo(arg))
  }
}

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

Table.js

const DetailPage = () => <View><Text>Just a mock page</Text></View>

class Table extends Component {
  keyExtractor = (item, index) => index;
  renderItem = (argOne, index) => {
    return (
      <ListItem
        onPress={() => this.props.navigate(argOne)}
        key={index} />
    )
  }
  render() {
    return (
      <View>
        <FlatList
          keyExtractor={this.keyExtractor}
          data={this.props.data}
          renderItem={this.renderItem}
          refreshControl={
            <RefreshControl
              onRefresh={this.props.functionTwo}
            />
          }
        />
      </View>
    ) 
  }
}
// react-navigation StackNavigator
export default Table = StackNavigator({
  Table: { screen: Table },
  DetailPage: { screen: DetailPage }
});

【问题讨论】:

    标签: reactjs react-native react-navigation


    【解决方案1】:

    您可以将StackNavigator 移动到Container.js

    export default StackNavigator({
      Table: { screen: connect(mapStateToProps, mapDispatchToProps)(Container) },
      DetailPage: { screen: DetailPage }
    });
    

    你也可以直接connectTable 而不是创建Container 包装类:

    connect(mapStateToProps, mapDispatchToProps)(Table)
    

    【讨论】:

      【解决方案2】:

      由于TableStackNavigator,您可以使用screenProps 属性将属性传递给它,如here 所述

      由 StackNavigator(...) 创建的导航器组件采用以下道具:

      screenProps - 将额外的选项传递给子屏幕,例如:

      最终结果是:

      class Container extends Component {
        render() {
          return (
            <View>
              <Table screenProps={{...this.props}} />
            </View>
          )
        }
      }
      

      您可以在Table 上以this.props.screenProps.data 访问它

      【讨论】:

        猜你喜欢
        • 2018-02-26
        • 2018-07-29
        • 2019-02-07
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        相关资源
        最近更新 更多