I have React Native project with Redux and I'm trying to connect the actions to the components.
I have App.js file without index.js file.
This is how I implement Redux:
App.js:
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Provider } from 'react-redux';
import store from './src/store/Store.js';
import AppNavigator from './src/navigation/AppNavigator';
export default function App(props) {
return (
<Provider store = { store }>
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
</Provider>
);
}
AppNavigator.js:
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import MainTabNavigator from './MainTabNavigator';
export default createAppContainer(
createSwitchNavigator({
Main: MainTabNavigator
})
);
MainTabNavigator.js: (Only the relevant part)
import React from 'react'
import {connect} from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';
import * as CounterActions from '../store/actions/CounterActions';
let HomePage = connect(state => mapStateToProps)(HomeScreen);
const HomeStack = createStackNavigator(
{
Home: HomePage,
},
config
);
const tabNavigator = createBottomTabNavigator({
HomeStack,
SettingsStack,
});
const mapStateToProps = (state) => {
return {
count: state.counter.count
}
};
const mapDispatchToProps = {
...CounterActions
};
export default tabNavigator;
CounterActions.js:
export const increment = (number) => {
return (dispatch) => {
dispatch({ type: 'INCREMENT', number })
}
};
export const decrement = (number) => {
return (dispatch) => {
dispatch({ type: 'DECREMENT', number })
}
};
The following line in MainTabNavigator.js connects the state to props of the HomeScreen component:
let HomePage = connect(state => mapStateToProps)(HomeScreen);
HomeScreen.js:
import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
export const HomeScreen = (props) => {
alert(JSON.stringify(props));
return (
<View style={styles.container}>
<Text>COUNT FROM STORE: {props.count}</Text>
</View>
);
};
HomeScreen components gets the state correctly and render 'count', but How do I connect the actions?
I want HomeScreen to dispatch like this:
props.increment(1);
Thanks!
The mapDispatchToProps is the second argument of the connect function from the react-redux.
I also think that you pass wrong the first argument to the connect.
Try this:
let HomePage = connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
Finally solved it by the following way:
MainTabNavigator.js:
import React from 'react'
import {connect} from 'react-redux';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';
import {increment, decrement} from '../store/actions/CounterActions';
let HomePage = connect(state => mapStateToProps, dispatch => mapDispatchToProps(dispatch))(HomeScreen);
const HomeStack = createStackNavigator(
{
Home: HomePage,
},
config
);
const tabNavigator = createBottomTabNavigator({
HomeStack,
SettingsStack,
});
const mapStateToProps = (state) => {
return {
count: state.counter.count
}
};
const mapDispatchToProps = (dispatch) => {
return {
increment: (number) => dispatch(increment(number)),
decrement: (number) => dispatch(decrement(number))
}
};
export default tabNavigator;
Follow along, we will make some modifications to your files:
First lets modify your MainTabNavigator.js since you only posted the relevant part, make sure to implement this for the rest as well.
import React from 'react'
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import {HomeScreen} from '../screens/HomeScreen';
let HomePage = connect(state => mapStateToProps)(HomeScreen); // <===== Remove this
const HomeStack = createStackNavigator(
{
Home: HomePage, // <===== Make this HomeScreen instead of HomePage
},
config
);
const tabNavigator = createBottomTabNavigator({
HomeStack,
SettingsStack,
});
const mapStateToProps = (state) => {
return {
count: state.counter.count
}
};
const mapDispatchToProps = {
...CounterActions
};
export default tabNavigator;
What we want is to have the mapping of state and props on the Home Screen itself (or any other screen)
Now lets move on to your HomeScreen.js:
import React from 'react';
import { connect } from 'react-redux';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { increment, decrement } from '../store/actions/CounterActions'; // <===== import your actions here, preferably like this
/** add the following: */
const mapStateToProps = (state, ownProps) => ({
// ... computed data from state and optionally ownProps
});
const mapDispatchToProps = {
// ... normally is an object full of action creators
increment, // <===== Map your dispatch here to props
decrement // <===== Mapping the second dispatch
};
const HomeScreen = (props) => {
alert(JSON.stringify(props));
return (
<View style={styles.container}>
<Text>COUNT FROM STORE: {props.count}</Text>
</View>
);
};
/** Export your component like this */
export default connect(
mapStateToProps,
mapDispatchToProps
)(HomeScreen)
Now anywhere on your HomeScreen.js you can call this.props.increment(yourNumber) or this.props.decrement(yourNumber) and you should be good to go
Hope this Helps!
Related
I'm new on react native. I have navigation (bottom navigation) with Setting screen and TopNavigation.
Inside TopNavigation I have dynamic tab with 1 screen (multiple tab with 1 screen). The problem is, MainComponent.js would receive the results at componentWillReceiveProps() and how to send or update data from nextProps to my specific dynamic tab? Or maybe my code in the wrong way?
You can see my image, my multiple tab with 1 screen, and have 1 button to fetch data. And this is my code:
index.js
import React from 'react';
import {AppRegistry} from 'react-native';
import {name as appName} from './app.json';
//Redux
import {applyMiddleware, createStore} from 'redux';
import {Provider} from 'react-redux';
//reducers
import allReducers from './App/reducers';
import MainContainer from './App/Containers/MainContainer';
//Redux saga
import createSagaMiddleware from 'redux-saga';
import rootSaga from './App/sagas/rootSaga';
const sagaMiddleware = createSagaMiddleware();
let store = createStore(allReducers, applyMiddleware(sagaMiddleware));
const Main = () => (
<Provider store={store}>
<MainContainer />
</Provider>
);
sagaMiddleware.run(rootSaga);
AppRegistry.registerComponent(appName, () => Main);
MainContainer.js
import {connect} from 'react-redux';
import MainComponent from '../Components/MainComponent';
import {fetchCategoriesAction} from '../actions/categoriesAction';
import {fetchTestAction} from "../actions/testAction";
const mapStateToProps = (state) => {
return {
receivedCategories: state.categoriesReducer,
receivedMovies: state.testingReducer,
navigation: state.navigation
}
};
const mapDispatchToProps = (dispatch) => {
return {
onFetchCategories: (payload) => {
console.log("mapDispatchToProps");
dispatch(fetchCategoriesAction(payload));
},
onFetchTest: (payload) => {
dispatch(fetchTestAction(payload))
}
};
};
const MainContainer = connect(mapStateToProps, mapDispatchToProps)(MainComponent);
export default MainContainer;
MainComponent.js
import React, {Component} from "react";
import {createAppContainer, createMaterialTopTabNavigator} from 'react-navigation'
import {createMaterialBottomTabNavigator} from "react-navigation-material-bottom-tabs";
import {tabBarOptions} from "../Navigation/Top/Options";
import Test from "./Screens/Test";
import Setting from "./Screens/Setting";
export default class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {myNavigator: null, movies: [], categories: []}
}
componentWillMount() {
this.props.onFetchCategories({p1: 1});
}
createNavigator(categories) {
if (categories != null) {
const screens = {};
categories.forEach(page => {
screens[page.slug] = {
screen: Test,
};
});
let TopNavigator = createMaterialTopTabNavigator(screens, {
tabBarOptions,
lazy: true,
});
const AppNavigator = createMaterialBottomTabNavigator({
B1: TopNavigator,
B2: Setting,
});
const AppContainer = createAppContainer(AppNavigator);
this.setState({myNavigator: <AppContainer screenProps={this.props}/>});
}
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
if (nextProps.receivedCategories !== null && nextProps.receivedCategories.categories !== this.state.categories) {
this.setState({categories: nextProps.receivedCategories.categories});
this.createNavigator(nextProps.receivedCategories.categories)
}
}
render() {
return this.state.myNavigator;
}
}
Test.js
import React, {Component} from "react";
import {Text, Container, Button} from 'native-base'
export default class Test extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Container>
<Button onPress={ () => {
this.props.screenProps.onFetchTest({slug: this.props.navigation.state.routeName})
}}><Text>Fetch Data</Text></Button>
<Text>Test screen {this.props.navigation.state.routeName}</Text>
<Text>I want this part changed when i click fetch data button</Text>
</Container>
)
}
}
Thank you!
I am trying to use switch navigator with redux. following is my code.
import { createSwitchNavigator, createStackNavigator } from 'react-navigation';
import LoginScreen from '../screens/LoginScreen';
import EmployeeListScreen from '../screens/EmployeeListScreen';
import DetailsView from '../screens/EmployeeDetailViewScreen';
import EmployeeForm from '../screens/EmployeeForm';
import AuthLoadingScreen from "../screens/AuthLoadingScreen.js";
import {connect } from "react-redux";
import { AppNavigator } from "../navigations/AppNavigator.js";
const AppStack = createStackNavigator({
List:{screen:EmployeeListScreen},
Detail:{screen:DetailsView},
Form:{screen:EmployeeForm}
});
const AuthStack = createStackNavigator({ Login: LoginScreen });
export const AuthNavigator = createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppNavigator,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
);
const AuthWithNavigationState = ({ dispatch, nav }) => (
<AuthNavigator />
);
const mapStateToProps = state => ({
nav: state.nav,
});
export default connect(mapStateToProps)(AuthWithNavigationState);
I'm importing this component is my App.js file and using it as follows to connect with redux store but it is giving me error like, React is not defined and error is located at connect(AuthWithNavigationState)
import React from 'react';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import AppReducer from './src/reducers/AppReducer';
import AuthWithNavigationState from './src/navigations/AuthNavigator.js';
const store = createStore(AppReducer,applyMiddleware(thunk));
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AuthWithNavigationState/>
</Provider>
);
}
}
I've tried to follow instruction from below link but still I am getting the same error.
how can i integrate redux store to react native?
Can anyone tell me what is wrong with my code?
after too much trying, I figure out that, The switch navigator don't need to be connect to the store, so below step was incorrect.
const AuthWithNavigationState = ({ dispatch, nav }) => (
<AuthNavigator />
);
const mapStateToProps = state => ({
nav: state.nav,
});
export default connect(mapStateToProps)(AuthWithNavigationState);
I simply exported AuthNavigator and imported in App.js and this worked for me.
import React from 'react';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import AppReducer from './src/reducers/AppReducer';
import AuthNavigatorfrom './src/navigations/AuthNavigator.js';
const store = createStore(AppReducer,applyMiddleware(thunk));
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AuthNavigator/>
</Provider>
);
}
}
I am new to react-native and I am trying to implement a simple application using StackNavigation and react-redux with welcome and signup screens. I have configured both the screens using StackNavigation but for some reasons , only the SignUp screen pops up when the app starts. Below are my files :
Index.js
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('MyApp', () => App);
App.js
import React, { Component } from 'react';
import { Provider, connect } from "react-redux";
import { addNavigationHelpers } from "react-navigation";
import StackNavConfig from "./js/config/routes";
import getStore from "./js/store";
const AppNavigator = StackNavConfig;
const initialState = AppNavigator.router.getActionForPathAndParams('Welcome');
const navReducer = (state = initialState, action) => {
const newState = AppNavigator.router.getStateForAction(action, state);
return newState || state;
};
const AppWithNavigationState = connect(state => ({
nav: state.nav,
}))(({ dispatch, nav }) => (
<AppNavigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
));
const store = getStore(navReducer);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppWithNavigationState />
</Provider>
);
}
}
export default App;
js/config/routes.js
import Welcome from "../components/Welcome/view/Welcome";
import SignUp from "../components/SignUp/view/SignUp";
import { StackNavigator } from "react-navigation";
const Routes = {
Welcome: { screen: Welcome , path: ''},
SignUp: { screen: SignUp , path : '/signup'},
};
const RoutesConfig = {
initialRouteName: 'Welcome',
headerMode: 'none',
};
export default StackNavConfig = StackNavigator(Routes, RoutesConfig);
store.js
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import getRootReducer from "./reducers/index";
export default function getStore(navReducer) {
const store = createStore(
getRootReducer(navReducer),
undefined,
applyMiddleware(thunk)
);
return store;
}
Below are my components
Welcome.js
import React from 'react';
import {
View,
Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/WelcomeActions";
import { welcomeStyles } from '../styles/WelcomeStyles';
class Welcome extends React.Component {
constructor(){
super();
this.state = { };
}
render(){
return (
<View style = {welcomeStyles.mainContainer}>
<Text>Welcome</Text>
</View>
);
}
}
export default connect(
state => ({
}),
dispatch => bindActionCreators(welcomeActions, dispatch)
)(Welcome);
SignUp.js
import React from 'react';
import {
View,
Image} from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as welcomeActions from "../actions/SignUpActions";
import { signUpStyles } from '../styles/SignUpStyles';
class Welcome extends React.Component {
constructor(){
super();
this.state = { };
}
render(){
return (
<View style = {signUpStyles.mainContainer}>
<Text>SignUp</Text>
</View>
);
}
}
export default connect(
state => ({
}),
dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);
I also have action and reducer files for each of my component.But they are blank as of now , since I haven't yet implemented the redux part.I am combining the reducers as below.
import { combineReducers } from "redux";
import welcomeReducer from "../components/Welcome/reducers/WelcomeReducer";
import signUpReducer from "../components/SignUp/reducers/SignUpReducer";
export default function getRootReducer(navReducer) {
return combineReducers({
nav: navReducer,
welcomeReducer : welcomeReducer,
signUpReducer : signUpReducer,
});
}
As mentioned before , even after setting the initialRouteName to Welcome in my routes.js , the SignUp screen appears first everytime I launch the app. Please help
I found out what was the issue. I was calling this.props.navigate inside the render function by mistake which was causing the navigation to different screen.
i am using react-navigation and redux in react-native.when i just used redux, the states can send to child by redux. but it don't work when i add react-navigation.
my navigation.js
import {StackNavigator} from 'react-navigation';
import Home from './modules/home/views/Home'
export const StackRouter = StackNavigator({
Main: {screen: Home},
initialRouteName: {screen: Home}
});
const firstAction = StackRouter.router.getActionForPathAndParams('Main');
const tempNavState = StackRouter.router.getStateForAction(firstAction);
const initialNavState = StackRouter.router.getStateForAction(
firstAction,
tempNavState
);
//navigationreducer
export const stackReducer = (state=initialNavState,action) => {
debugger
const newState = StackRouter.router.getStateForAction(action, state);
return newState || state;
};
my store.js
import React, {Component} from 'react';
import { connect, Provider } from 'react-redux';
import {createStore, combineReducers, bindActionCreators, applyMiddleware } from 'redux';
import {addNavigationHelpers} from 'react-navigation'
import thunk from 'redux-thunk'
import PropTypes from 'prop-types'
import {StackRouter, stackReducer} from './router'
import home from './modules/home';
//routerConmponent
class RouterAppWithState extends Component {
constructor(props){
super(props)
}
render() {
return (
<StackRouter navigation={addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.router,
})} />
);
}
}
//all reducer
const reducer = combineReducers({
home: home.reducer,
router: stackReducer,
});
const mapActionToProps = (dispatch) => {
return {
home_actions: bindActionCreators(home.actions, dispatch)
}
};
const mapStateToProps = (state) => {
debugger;
return state
};
//connect redux and navigation
const StoreApp = connect(mapStateToProps, mapActionToProps)(RouterAppWithState);
const store = applyMiddleware(thunk)(createStore)(reducer);
export default class RootApp extends Component{
render() {
return(
<Provider store={store}>
<StoreApp />
</Provider>
)
}
}
my home.js ,just import actions and reducers, and export the module
import actions from './store/actions';
import reducer from './store/reducer'
export default {
actions,
reducer
}
my reducers
export default(state=states, action) => {
let newState = {...state};
switch (action.type){
case TYPES.ADD_COUNT: newState.count = state.count+1;break;
default: break;
}
return newState
};
my actions
const add_count = () => {
console.log('add');
return async (dispatch) => {
dispatch({type: TYPES.ADD_COUNT});
await new Promise((resolve) => {setTimeout(() => {resolve()} , 3000)});
dispatch({type: TYPES.ADD_COUNT});
};
};
export default {
add_count
}
my view Home.js
import React, {Component, StyleSheet} from 'react';
import {View, Text, Button} from 'react-native';
export default class Home extends Component{
constructor(props){
super(props)
}
// static contextTypes = {
// navigation: React.PropTypes.Object
// };
render() {
debugger
const {add_count} = this.props.home_actions;
const {count} = this.props.home;
return (
<View>
<Text >{count}</Text>
<Button onPress={add_count} title={'add count'}/>
{/*<Button onPress={() => {navigation.navigate('live')}} title={'live'}/>*/}
</View>
)
}
}
In Home.js function render, this.props is
{
navigation: Object,
screenProps: undefined
}
has not states in redux. but without react-navigation, this.props is
{
home: Object,
home_actions: Object
}
thanks
The reason is because now the StackRouter is controlling the rendering of your Home page. The router only pass down a prop called navigation and whatever you pass down from screenProps.
There are two ways that you can achieve a similar behavior as before:
1) In RouterAppWithState's render function, pass down this.props into screenProps like this
<StackRouter navigation={addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.router,
})}
screenProps={this.props}
/>
2) (recommended) The other way is to directly use connect on your home page to connect your Home component to the store and access home specific part of the store. i.e. connect(mapStateToProps)(Home)
I have followed this great tutorial which is Tab Bar with three tabs using redux. Everything works great. Now I am trying to nest this Tab Bar inside Stack Navigator but I have the following error:
I am new to Redux and really cannot find where is the problem. Here is my code:
StackNav.js
import React from 'react';
import { connect } from 'react-redux';
import { addNavigationHelpers } from 'react-navigation';
import { RootNav } from './../navigationConfiguration';
const mapStateToProps = (state) => {
return { navigationState: state.nav };
};
class StackNav extends React.Component {
render() {
const { dispatch, navigationState } = this.props;
return (
<RootNav
navigation={
addNavigationHelpers({
dispatch,
state: navigationState,
})
}
/>
);
}
}
export default connect(mapStateToProps)(StackNav);
StackNav's navigationConfiguration.js
import { StackNavigator } from 'react-navigation';
import TabBarNavigation from './../tabBar/views/TabBarNavigation';
import Welcome from './../../Screens/Register/Welcome.js';
const routeConfiguration = {
Welcome: { screen: Welcome },
Home: { screen: TabBarNavigation },
};
const stackNavigatorConfiguration = {
initialRouteName: 'Welcome',
headerMode: 'screen',
navigationOptions: {
header: { visible: false }
}
};
export const RootNav = StackNavigator(routeConfiguration, stackNavigatorConfiguration);
Reducers
import { combineReducers } from 'redux';
// Navigation
import { AppNavigator } from './../stackNav/navigationConfiguration';
import { NavigatorTabOne } from './../tabOne/navigationConfiguration';
import { NavigatorTabTwo } from './../tabTwo/navigationConfiguration';
import { NavigatorTabThree } from './../tabThree/navigationConfiguration';
export default combineReducers({
nav: (state, action) => AppNavigator.router.getStateForAction(action, state),
tabOne: (state, action) => NavigatorTabOne.router.getStateForAction(action, state),
tabTwo: (state, action) => NavigatorTabTwo.router.getStateForAction(action, state),
tabThree: (state, action) => NavigatorTabThree.router.getStateForAction(action, state),
});
I also tried with this reducer instead nav: above
import { AppNavigator } from './../stackNav/navigationConfiguration';
const initialState = AppNavigator.router.getStateForAction(AppNavigator.router.getActionForPathAndParams('Welcome'));
export const navReducer = (state = initialState, action) => {
const nextState = AppNavigator.router.getStateForAction(action, state);
return nextState || state;
};
Start point of the app:
import React from 'react';
import {
AppRegistry,
Text
} from 'react-native';
import { Provider } from 'react-redux';
import StackNav from './../App/stackNav/views/StackNav';
import store from './store';
Text.defaultProps.allowFontScaling = false;
class App extends React.Component {
render() {
return (
<Provider store={store}>
<StackNav />
</Provider>
);
}
}
AppRegistry.registerComponent('MyApp', () => App);
I will appreciate any help. Thank you in advanced!
well, you're importing AppNavigator when you shoould be importing { RootNav } in reducer index
I don't have a direct answer to your question, but I can offer an example of how to nest Tab Navigators in Stack Navigators in this tutorial - https://developerlife.com/2017/04/15/navigation-and-styling-with-react-native/
Here's the JS class (from the tutorial and it's GitHub repo) that sets up the navigators and nesting - https://github.com/r3bl-alliance/react-native-weather/blob/master/app/Router.js