Someone now how to pass parameters effectively with navigation.reset() function?
I have tried to pass parameters to the react-navigation reset function but got always undefined so far
First try:
import {CommonActions} from '#react-navigation/native';
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [
{
name: 'ConnectionStack',
params: {zob: 'zob'},
},
],
}),
);
Second try:
const MyComponent = ({navigation}) => {
navigation.reset({
index: 0,
routes: [{name: 'ConnectionStack', params: {zob: 'zob'}}],
});
};
params are always undefined but my navigation is reset like I want.
Related
I have a component with the object "project_element" and I want to transfer the object to another component through the "vue-router".
This is the code from my first component which opens the second component if the user clicks on the button.
<router-link :to="{ name: 'project', params: { project_url: project_element.project_name, project_element: project_element} }">
<b-button> Open </b-button>
</router-link>
This is the code from my Vue Router in index.js
{
path: '/projects/:project_url',
component: SingleProjectViewApp,
name: 'project',
props: { project_element: project_element }
},
I already managed to set the "project_element.project_name" to the url but I also need the "project_element" itself in my second component.
In the compenent I have set the object in the "props section"
props: {
project_element: {
type: Object,
required: true
}
},
The problem is in the Vue Router, I can't pass the project_element like a variable, only with quotation marks. But then I get an error because obviously the component expected an object and not a string.
Thanks for your help!
Try this in your router
path: '/projects/:project_url?',
component: SingleProjectViewApp,
props(route) {
const props = {
projectElement: route.params.project_url
};
return props;
}
and in your props change "project_element" to "projectElement" (generally you want to do camel case in vue props)
props: {
projectElement: {
type: Object,
required: true
}
},
The first thing that came to my mind is JSON.stringify() and JSON.parse(). Although I am not sure this is a perfect solution.
Any way try this:
<router-link :to="{ name: 'project', params: { project_url: project_element.project_name, project_element: JSON.stringify(project_element)} }">
<b-button> Open </b-button>
</router-link>
// router.js
{
path: '/projects/:project_url',
component: SingleProjectViewApp,
name: 'project',
props(route) {
return {
project_element: JSON.parse(route.params.project_element),
}
}
},
Note: I honestly think this is an antipattern and you should use different aproach for comunicating through components. custom-events, centralized-state, event-bus or even provide & inject will all be better for that kind of work.
routes: [
{
path: '/',
name: 'start',
component: Start,
meta: {
my_data: "my data here",
},
},]
to get data inside the component
this.$route.currentRoute.meta.my_data
UPDATE
this.$route.push("/"+ JSON.stringify(data) )
routes: [
{
path: '/:data',
name: 'start',
component: Start,
},]
to get data inside the component
JSON.parse(this.$route.params.data)
Problem: I have a component that needs a boolean value optionally passed to it as part of a call from within the view app and from an external app. When I invoke the router directly I can pass the boolean with no issues but if I route by using the actual URL I get a parse warning. To prevent the warning should I be using a string instead and parse it myself?
Router:
export default new Router({
routes: [
{
path: '/foo',
name: 'Foo',
component: Foo,
props: (route) => ({ booleanParam: route.query.booleanParam })
}
]
})
Component:
<template>
<div>
BooleanParam: {{booleanParam}}
</div>
</template>
<script>
export default {
name: 'Foo',
props: {
booleanParam: {
type: Boolean,
required: false
}
}
}
</script>
Works:
router.push( { name: 'Foo', query: { booleanParam: true } })
Generates Warning:
http://localhost:8080/foo?booleanParam=true
Warning:
[Vue warn]: Invalid prop: type check failed for prop "booleanParam".
Expected Boolean, got String.
If a boolean is required by the component then parse the value as a Boolean before setting this as a prop:
props: (route) => ({ booleanParam: (route.query.booleanParam === 'true') })
This way the correct type is ensured.
EDIT:
As noted in the comment by the OP to support both String and Boolean the parameter could be converted to String to ensure both types work:
props: (route) => ({ booleanParam: (String(route.query.booleanParam). toLowerCase() === 'true') })
have you try this
const router = new VueRouter({
routes: [
{
path: '/foo',
name:"Foo"
component: Foo, props: (route) => ({ query: route.query.q }) }
]
})
OR
{path:'/foo/:booleanParam', name:'Foo', component: Foo }
I've read countless react-navigation docs, and I know there is way to do this, but it's definitely what I would call non-trivial and definitely non-intuitive.
I have a root navigation stack:
export const NavigationStack = StackNavigator({
Splash: {
screen: Splash
},
Signup: {
screen: Signup
},
Login: {
screen: SignIn
},
ForgottenPassword: {
screen: ForgottenPassword
},
Discover: {
screen: Discover
},
ProfileShow: {
screen: ProfileShow
}
}, {
headerMode: 'none'
})
The ForgottenPassword screen is a child Stack Navigator:
import { StackNavigator } from 'react-navigation'
import PasswordResetProcess from './index'
const ForgottenPassword = StackNavigator({
ResetPassword: {
screen: PasswordResetProcess
}
}, {
headerMode: 'none'
})
export default ForgottenPassword
On that index.js Container Component, there is a sub-component that I pass navigation to, like this:
switch (lastCompletedStep) {
case NEW_RESET_REQUEST:
return <InputTel navigation={navigation} />
case INPUT_TEL:
return <ResetPassword navigation={navigation} />
That ResetPassword component is the one in question. It triggers an action creator and passes this.props.navigation into the action creator:
await props.handleResetSubmit(token, props.navigation)
From inside this action creator, props.navigation is available as navigation. I can do this fine:
navigation.navigate('Discover') // see how this is from the root Navigation Stack
I cannot, however, do this:
navigation.dispatch({
type: 'Navigation/RESET',
index: 0,
actions: [{ type: 'Navigate', routeName: 'Discover' }]
})
It throws this error:
[edit] I just tried this and it also generated the same error:
navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Discover' })]
}))
How do I reset the stack while navigating to Discover from here?
I feel like the answer is to navigate to discover and reset the stack at the same time as some kind of child operation, but I don't know where to begin putting that together. The react-navigation documentation is horrendous for illustrating child to parent operations.
Here is my best guess at what it approximately has to look like:
navigation.dispatch({
type: 'Navigation/NAVIGATE',
routeName: 'Discover',
actions: [{ type: 'Reset', index: 0, key: null }]
})
I just solved it with this code:
navigation.dispatch(NavigationActions.reset({
index: 0,
key: null,
actions: [NavigationActions.navigate({ routeName: 'Discover' })]
}))
The secret was to add key: null, which I have seen people doing before. It is a very important element for times when you are resetting.
Here is the documentation I found that illustrates it:
https://github.com/react-community/react-navigation/issues/1127
I think this works because NavigationActions has knowledge of the root navigation stack, so it works for the same reason navigation.navigate('Discover') worked (in the context of my code in this question).
in version >2 of react navigation, NavigationActions.reset() doesnt work.
You should use StackActions.reset() instead:
import { NavigationActions, StackActions } from 'react-navigation';
const resetStackAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Discover' })],
});
this.props.navigation.dispatch(resetStackAction);
I have few screens which I navigate through one by one. Screen1->screen2-screen3->screen4-Home
What I want is when I go to home then the previous history of navigation should be cleared and back pressing back button should not go to last navigated screen which is screen 4. Currently When I press back button on home screen it takes me back to the last route in the stack which is screen4. I have used below code. It is giving me error no route defined or key Home. Which I have already defined in Screens class. Any help would be appreciated.
const resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Home' })],
});
onPress={() => this.props.navigation.dispatch(resetAction)}
in V5, you can use
this.props.navigation.reset({
index: 0,
routes: [{name: 'Home'}],
});
Using hooks
import {useNavigation} from '#react-navigation/native';
const navigation = useNavigation();
navigation.reset({
index: 0,
routes: [{name: 'Events'}],
});
As it states in the react-navigation docs for reset action, index should be the current active route's index. The error might be related to that.
How to use the index parameter
The index param is used to specify the
current active route. eg: given a basic stack navigation with two
routes Profile and Settings. To reset the state to a point where the
active screen was Settings but have it stacked on top of a Profile
screen, you would do the following:
import { NavigationActions } from 'react-navigation'
const resetAction = NavigationActions.reset({
index: 1,
actions: [
NavigationActions.navigate({ routeName: 'Profile'}),
NavigationActions.navigate({ routeName: 'Settings'})
]
})
this.props.navigation.dispatch(resetAction)
import {NavigationActions} from 'react-navigation';
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'HomeScreen'})
] })
this.props.navigation.dispatch(resetAction);
you can use this, this works for me..
If you use react-navigation#<=4 you can use a Switch Navigator.
You create a Switch Navigator with createSwitchNavigator.
Such navigators do not stack up your navigation.
Add your auth screen/navigator in a Switch Navigator with the home screen/stack.
With that, when you navigate from home to log in, the stacks are not kept.
For more on it:
https://reactnavigation.org/docs/4.x/auth-flow/
With #react-navigation 5.x you can use CommonActions to reset/clear the stack. I'll leave an example here.
import { CommonActions } from '#react-navigation/native';
const handleSigninNavigation = () => {
navigation.dispatch(
CommonActions.reset({
index: 0,
routes: [{ name: "your-new-route" }]
}));
}
Also you can create your own stack while resetting it. Just pass the names of the routes to routes array and give an index to navigate first.
CommonActions.reset({
index: 1,
routes: [{ name: "home" }, { name: "signin" }]
}));
Above code will reset the current stack with given routes and will navigate to the signin since we set the index to 1.
With typed routes and their parameters
type StateRoute<Route extends keyof MyNavigatorParamList> = {
name: Route;
params: MyNavigatorParamList[Route];
};
const toNavigationStateRoutes = <Route extends keyof MyNavigatorParamList>(
...routes: StateRoute<Route>[]
) => routes;
navigation.dispatch(
CommonActions.reset({
index: 1,
routes: toNavigationStateRoutes(
{
name: 'Home',
params: undefined,
},
{
name: 'Some screen',
params: { id: "..." },
},
),
}),
);
//import
import { NavigationActions, StackActions } from 'react-navigation';
//reset current navigation stack and create new navigation stack
const loginScreenAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'LoginScreen' })],
});
//open new component with new navigation stack
this.props.navigation.dispatch(loginScreenAction)
There is a vue royter
.....
const Edit = Vue.component('edit', require('./components/pages/edit.vue'));
const Product_category = Vue.component('home', require('./components/pages/product_categories.vue'));
const routes = [
........
{
path: '/product_categories',
name: 'product_categories',
component: Product_category
},
{
path: '/product_categories/edit/:id',
name: 'product_categories_edit',
components: {default: Edit, entity: Product_category},
props: {default: true, entity: true}
}
];
How can I get data in component Product_category componate Edit?
<script>
export default {
props: ['id', 'entity'],
mounted: function () {
console.log('Admin edit page mounted.');
console.log(this.entity); // Eror
console.log(entity); // Eror
this.getData();
},
}
</script>
A direct appeal is not suitable, because each router will have its own entity.
Use vuex if you prefer a global state-object. It's properties can be mapped to each instance and component https://github.com/vuejs/vuex
If you prefer an event based approach use an event bus https://alligator.io/vuejs/global-event-bus/
It is all well described at multiple positions in the official vuejs documentation.