简体   繁体   中英

How can I set the initial state using react-navigation v5 to include screens as history?

Let's say I have the following route structure:

Authenticated
    - Main
        - StackA
            -ViewA
        - StackB
            -ViewB
        - StackC
            - ViewC
            - ViewD

I want to set my initial state so that I'm looking at ViewD but I can swipe from the left to go back to ViewC.

The documentation here https://reactnavigation.org/docs/navigation-state/#partial-state-objects says that I should be able to provide an array of objects, each of which have a name property mapping to a route name, to the routes property of the initial state and it will sort the rest out for me. However, when I do so, nothing changes and the usual initial state is rendered.

This is the initial state that I would expect to work, based on the documentation linked above:

{
  routes: [
    { name: "Authenticated" },
    { name: "Main" },
    { name: "StackC" },
    { name: "ViewC" },
    { name: "ViewD" }
  ]
}

Edit
I managed to get around the issue by using the following initial state:

{
  routes: [
    {
      name: "Authenticated",
      params: {
        screen: "StackC",
        params: {
          screen: "ViewD",
          initial: false,
        }
      }
    }
  ]
}

The key part of this is the initial property. This causes the initial route of StackC to be rendered underneath ViewD , which is exactly what I wanted.

Here's a quick example I created on snack . Basically, you need to create an array of screens, and use the reset function.

    const initialState = {
    index: 4,
    routes: [
      {
        name: 'Stack',
        params: { screen: 'StackView1' },
      },
      {
        name: 'Stack',
        params: { screen: 'StackView2' },
      },
      {
        name: 'Stack1',
        params: { screen: 'Stack1View1' },
      },
      {
        name: 'Stack1',
        params: { screen: 'Stack1View2' },
      },
      {
        name: 'Stack1',
        params: { screen: 'Stack1View3' },
      },
    ],
  };
  return (
    <NavigationContainer initialState={initialState}>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM