react-nativereduxreact-native-navigationwix-react-native-navigationreact-native-navigation-v2

React-Native-Navigation V2 with redux cannot pass props


I have a simple two screens app with redux and React-Native-Navigation V2. I try to pass an item from a list to another view as a prop. Unfortunately, I get an error:

TypeError: Cannot read property 'id' of undefined

The item is passed but not received as a prop in the second view. Everything works fine when working without Redux. Am I registering the views correctly?

Views registration:

export default (store) =>  {
  Navigation.registerComponent('example.app.FirstScreen', reduxStoreWrapper(FirstScreen, store));
  Navigation.registerComponent('example.app.SecondScreen', reduxStoreWrapper(SecondScreen, store));
}

function reduxStoreWrapper (MyComponent, store) {
  return () => {
    return class StoreWrapper extends React.Component {
      render () {
        return (
          <Provider store={store}>
            <MyComponent />
          </Provider>
        );
      }
    };
  };
}

First View:

class FirstScreen extends Component {
  componentDidMount() {
    this.props.listItems();
  }

  onItemPress = (item: Item) => {
    Navigation.push(item._id, {
      component: {
        name: 'example.app.SecondScreen',
        passProps: {
          item: item
        }
      }
    });
  };

  render() {
    return (
      <View>
        <ItemsList items={this.props.items} onItemPress={this.onItemPress}/>
      </View>
    );
  }
}

const mapStateToProps = state => {
  let items = state.itemsReducer.items.map(item => ({ key: item.id, ...item }));
  return {
    items: items
  };
};

const mapDispatchToProps = {
  listItems
};

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

Second View:

class SecondScreen extends Component {
  static propTypes = {
    item: PropTypes.object.isRequired,
  };

  componentDidMount() {
    const { item } = this.props;
    this.props.listSubitems(item.id);
  }

  render() {
    const { subitems } = this.props;
    return (
      <View>
        <SubitemsList subitems={subitems}/>
      </View>
    );
  }
}

const mapStateToProps = state => {
  let subitems = state.subitemsReducer.subitems.map(subitem => ({ key: subitem.id, ...subitem }));
  return {
    subitems: subitems
  };
};

const mapDispatchToProps = {
  listSubitems
};

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

Solution

  • Views should be registered this way:

    export default (store, Provider) =>  {
      Navigation.registerComponentWithRedux('example.app.FirstScreen', () => FirstScreen, Provider, store);
      Navigation.registerComponentWithRedux('example.app.SecondScreen', () => SecondScreen, Provider, store);
    }