Having trouble linking multiple components using redux in react native

I'm having trouble figuring out how to connect two different components using the redux store.

Here's what I've attempted:

View.js

import React from 'react';
import {View, Text, Button} from 'react-native';
import {Actions} from 'react-native-router-flux';

export default ({counter, actions: { incrementCounter }}) => (
  <View>
    <Text>Hello from page 1</Text>
    <Button title='Go to page 2' onPress={() => Actions.page2({})} />
    <Button title='Go to page 3' onPress={() => Actions.page3({})} />
    <Button title='INCREMENT' onPress={() => incrementCounter()} />
    <Text>{counter}</Text>
  </View>
);

Page2.js

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

import { Actions } from 'react-native-router-flux';
import { incrementCounter } from '../actions';

export default ({ counter, actions: { incrementCounter } }) => (
  <View>
    <Text>Hello from page2</Text>
    <Button title='Go to Page 1' onPress={() => Actions.page1({})} />
    <Button title='Go to Page 3' onPress={() => Actions.page3({})} />

    <Button
      title='Increment'
      onPress={() => incrementCounter()}
    />
    <Text>{counter}</Text>
  </View>
);

index.js

import React, { Component } from 'react';
import { View, div } from 'react-native';

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

import Page1 from './View';
import Page2 from '../Page2';
import * as actionCreators from '../../actions';


class AllComp extends Component{
 render(){
     const { counter, actions } = this.props;
     return(
      <View>
       <Page1 counter={counter} actions={actions} />
       <Page2 counter={counter} actions={actions}/>
      </View>
    )
  }
}

function mapStateToProps(state){
  return{
    counter: state.counter,
  }
}

function mapDispatchToProps(dispatch){
  return{
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

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

The result I got after running the code is a bit unexpected.

It shows the content of both View.js and Page2.js on the same page.

I learned that in order to connect multiple components, I need to wrap them into one, which I did. However, the output turned out differently than expected.

Answer №1

You've successfully created a single view that contains two pages:

  <View>
   <Page1 counter={counter} actions={actions} />
   <Page2 counter={counter} actions={actions}/>
  </View>

Since both pages are displayed on the same screen, it's important to follow the React-native-router-flux documentation and specify routes in your App.js as shown below:

const App = () => (
  <Router>
    <Stack key="root">
      <Scene key="page1" component={Page1} title="Page 1"/>
      <Scene key="page1" component={Page2} title="Page 2"/>
    </Stack>
  </Router>
);

To connect multiple components to Redux, remember to avoid wrapping them in the same component. Instead, use the connect function to link them to Redux individually by implementing the following functions within each component you want to connect:

function mapStateToProps(state){
  return{
    counter:state.counter,
  }
}

function mapDispatchToProps(dispatch){
  return{
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A step-by-step guide on smoothly transitioning between elements using Vue-Carousel on a click event

Today marks my first question here and I'm excited! Can anyone guide me on how to implement sliding on click element with Vue-Carousel? I want to slide to the right with just a single click on my input button. Here's the code snippet I have base ...

Is it possible to display the command output in Grunt as it runs?

When I run this command, I am not seeing any output and it runs endlessly: grunt.registerTask('serve', function () { var done = this.async(); grunt.util.spawn({ cmd: 'jekyll', args: ['serve'], ...

Which is better: JQuery, YUI, or another option for JavaScript and CSS frameworks?

It's been about 6 years since I last dipped my toes into web development. Attempting to re-enter the field, I find myself overwhelmed by all the new technologies and trends. For my upcoming project, I've decided to go with Perl and Catalyst. The ...

Utilizing Javascript to retrieve the current Controller and Action in Rails

Is it possible for JavaScript to determine the current controller and action in Rails? I had the idea of creating a hidden container to store the current controller and action, but I'm curious if there is a specific JavaScript function for this purpo ...

Troubleshooting issue with changing class based on input values

It appears that there is an issue with the functionality when switching values on page load. Initially, I was able to make it work for a single switch, but now that there are multiple switches on the page, toggling affects all of them. How can I modify it ...

Top tip: Utilize jQuery for the most effective method of adding content to the HTML of a paragraph situated

One interesting challenge I'm facing involves a textarea that stores dynamic HTML content within paragraph (p) tags. Initial HTML: <textarea rows='7' class='form-control' id='comments'><p>My variable HTM ...

Is React the ideal choice for implementing a shared state subscription mechanism in your project?

Trying to determine if this falls under the "pub/sub" pattern or a variation of it. The goal is to establish a shared state where different components can subscribe to it and only receive updates when the state changes. const useForceUpdate = () => useR ...

Is there a way to grab code from a different HTML page using JavaScript and jQuery when the user clicks on something?

After testing various codes for the intended purpose mentioned in the title, I have observed a peculiar behavior. The code from settings.html appears briefly and then disappears rapidly. Javascript: function load() { $("#paste").load("settings.html") ...

Unable to modify existing attributes in a sails.js model

I'm new to sails.js and I have a question about adding fields to an existing model in Sails.js. Here is the current model: module.exports = { attributes: { id: { columnName: 'id', type: 'integer&apos ...

Can you attach a jQuery function to multiple CSS selectors at once?

Is it feasible to bind a mouseout call to two CSS selectors in order to trigger another action when the mouse moves away from both elements simultaneously? ...

There appears to be an issue with the functionality of the external CSS pathway

placeholder image hereplaceholder image hereplaceholder image here I'm encountering a problem and struggling to identify the mistake in my current approach. ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

My divs are multiplying twice as fast with every iteration of the Javascript For Loop

Recently, I developed a script that generates a series of fields based on a number provided by the user (k). Initially, I had a script that would create the correct number of fields. However, I decided to arrange them like vectors on the screen, so I made ...

"Exploring the power of Node.js by utilizing ObjectArray and implementing

Can I compare two arrays of objects in JavaScript? My goal is to find the common objects between these two arrays: First object array: [ { id_0: 356, name_0: 'xxxxx', id_1: 33, name_1: 'yyyyyy', id_ ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...

Convert form data into a JSON object using Vue.js

I'm attempting to generate a JSON object from the submitted form data. Fortunately, I've accomplished this using a variable. However, is there an alternative approach for creating a JSON object? Form <form @submit.prevent="submit"& ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Vue-Apollo - The 'value' property is not present in the 'Readonly<Ref<Readonly<any>>>' type

MY CURRENT DILEMMA: In my quest to seamlessly integrate vue-apollo v4 with Typescript, I have encountered a challenge. I am in the process of retrieving data from a simple query using useQuery along with useResult. The default return type of useResult i ...

Load an image dynamically within a JavaScript function

I'm currently utilizing a Javascript photo viewer plugin (found here: http://www.photoswipe.com/). My goal is to dynamically update the photos connected to the plugin as the user swipes through different images. To achieve this, I am using a Javascri ...

Using a ThreeJS bitmap texture to extrude a shape created with THREE.Shape

I have successfully created a cube with rounded corners using the THREE.Shape object: var shape = new THREE.Shape(); x = width/2; y = height/2; shape.moveTo(x - radius, y); //*** Top right x = -width/2; y = height/2; shape.lineTo(x + radius, y); if (tr) ...