Administration af tilstand i en React Navigation-app med Redux

I denne vejledning vil jeg vise, hvordan du styrer navigation og applikationstilstand ved at oprette en simpel app med React Navigation og Redux.

Forudsætning : Du skal allerede være fortrolig med React Native, React Navigation og Redux. Hvis du lige er kommet i gang med React Native, kan jeg varmt anbefale dette kursus:

  • Komplet React Native og Redux Course

Applikationsoversigt

Vi skal bygge en app lavet af to sider:

  • Hovedside : Dette viser en containervisning med en bestemt baggrundsfarve og en knap. Når der trykkes på knappen, vises den anden side.
  • Vælg farveside : Dette viser RØDE, GRØNNE og BLÅ knapper. Når en farve er valgt, vender appen tilbage til hovedsiden og viser den opdaterede baggrundsfarve.

Ved at oprette denne app lærer du:

  • Sådan navigerer du mellem forskellige skærme med React Navigation
  • Sådan bruges reducere og handlinger til at opdatere applikationstilstand, så handlinger på et skærmdrev UI ændres på et andet

Med denne viden kan du opbygge mere komplekse apps.

Bemærk: I resten af ​​denne tutorial bruger jeg udtrykkene "side" og "skærm" til at betyde det samme.

Projektopsætning (Expo)

Vi skal bygge denne app med Expo XDE.

Du kan downloade Expo til dit operativsystem fra Expo XDE GitHub-siden.

Gå derefter over til installationsinstruktionerne på Expo Docs. Disse viser dig, hvordan du installerer XDE på dit skrivebord og kører apps i Expo på simulator / enhed.

Da vi kører appen på simulatoren, skal du også downloade Xcode eller Android Studio.

Efter lanceringen af ​​Expo præsenteres denne side:

  • Vælg "Opret nyt projekt ..."
  • Vælg den tomme skabelon, og navngiv projektet redux-navigation

Projektet oprettes, hvorefter React Native Packager starter.

For at køre appen i simulatoren skal du vælge Enhed -> Åbn i iOS Simulator .

Når simulatoren er startet op, vises følgende skærmbillede:

Da projektet nu er oprettet, kan det åbnes med din valgte redaktør. Jeg bruger Visual Studio Code med udvidelsen React Native Tools.

Opbygning af appen

Før vi kan kode vores app, skal vi installere alle de afhængigheder, den har brug for.

Åbn en terminal, flyt til den projektmappe, du oprettede i Expo, og skriv:

npm install --save react-navigation redux react-reduxnpm install

Sørg derefter for at trykke på Genstart-knappen i Expo . Hvis du ikke gør dette, genkendes de nye afhængigheder ikke, og simulatoren kaster en rød fejlskærm, hvis du prøver at bruge dem.

Tid til at oprette vores app. Jeg organiserede mine projektmapper sådan:

/src /actions ColorChangedAction.js /components AppNavigator.js ChooseColorPage.js MainPage.js /reducers AppReducer.js ColorReducer.js NavReducer.js /state Colors.js

Du kan replikere den samme struktur fra din terminal:

cd redux-navigationmkdir src && cd srcmkdir actions && cd actions && touch ColorChangedAction.js && cd ..mkdir components && cd components && touch AppNavigator.js ChooseColorPage.js MainPage.js && cd ..mkdir reducers && cd reducers && touch AppReducer.js ColorReducer.js NavReducer.js && cd ..mkdir state && cd state && touch Colors.js && cd ..

Kopier og indsæt følgende kode i Colors.jsfilen:

Opret derefter den MainPagemed en standard baggrundsfarve og en knap:

Et par noter:

  • MainPage er en React-komponent snarere end en statsløs funktionel komponent, fordi den skal have adgang til applikationstilstand
  • Jeg bruger flex: 1, alignSelf: 'stretch'til at få containervisningen til at strække sig til hele skærmen
  • Farven på containervisningen er defineret i selectedColor()metoden, som prøver REDfra vores COLORStabel, og returnerer den tilsvarende hex-kode
  • Jeg har tilføjet en tom onChooseColor()håndterer til knappen tryk på begivenheden. Vi tilføjer kroppen til denne metode senere.

Tid til at tilslutte vores MainPagei vores rodfil App.js. Udskift det gamle indhold med dette:

Forfriskning af simulatoren giver dette:

Ikke smuk, men det viser baggrundsfarven og vores knap som beregnet.

Her er et øjebliksbillede af det, vi hidtil har bygget: GitHub Code Snapshot 1.

Tilføjelse af navigation

Vi er nu klar til at tilføje lidt navigation til vores app.

For at gøre dette skal du åbne AppNavigator.jsfilen og tilføje dette indhold:

Denne kode er lånt fra Redux-eksemplet i reaktionsnavigationsprojektet.

It defines a StackNavigator, using our MainPage as its main screen.

It also sets up AppWithNavigationState, a top-level container holding the navigation state. If this seems unclear, don’t worry. This is standard boilerplate code in React Navigation and we’ll just use it for now to get things going.

Time to write the navigation reducer, which will hold the navigation state inside the Redux store. Open the NavReducer.js file and add the following:

This reducer defines the initial navigation state of our app. Again, boilerplate code.

Now, let’s open the AppReducer.js file and add this:

As our application grows, we may need other reducers alongside our NavReducer. So we can combine them all together inside AppReducer.

Finally, we’re able to update our App.js to use all these new goodies:

The render method returns a provider with the created redux store, and holds our top-level component. Again, this is just boilerplate code needed to hook things up with Redux.

If we refresh the simulator, we now see a navigation bar appearing on top:

After all this code, you may get some errors on your simulator if anything is missing. If so, use this code snapshot to get back on track: GitHub Code Snapshot 2.

Show the Choose Color Page

Now that we have a MainPage inside a StackNavigator, we’re ready to add the ChooseColorPage so we can navigate to it.

Open the ChooseColorPage.js file and add the following code:

A few notes:

  • The code in the render() method iterates through each color, and maps it into a Button. The title and color properties are set.
  • When the button is tapped, the onSelectColor() handler is called with the appropriate color key.
  • The navigation object is accessible via props. In fact, it is injected into all the screens in our AppNavigator.
  • Calling this.props.navigation.goBack() takes us back to the previous screen in the AppNavigator.
  • At this stage, colorName is not yet used to set any state.

Next, we have to make our AppNavigator aware of the new ChooseColorPage screen. Let’s update it in the AppNavigator.js file:

Finally, add the code to navigate to the ChooseColorPage when the Choose Color button is tapped on the MainPage.

If we refresh the simulator now and tap on Choose Color, the app navigates to the new screen, which shows three buttons:

Note: Calling navigation.navigate('ChooseColor') works because we have named ChooseColor as one of the routes in our AppNavigator.

Tapping on the back button or on any of the color buttons brings us back to the main page, but the background color doesn’t change according to our selection.

Let’s fix that in the next section.

Again, if something is not working, you can get my saved code snapshot to this point: GitHub Code Snapshot 3.

Managing application state

We’ll use Redux to set the background color of our MainPage as our application state.

To do this, we need to define a Color Changed action, and a Color Reducer.

Open the ColorChangedAction.js file and add the following:

Then, open ColorReducer.js add add this:

In order for this reducer to be used, we need to add it to the AppReducer.js like so:

Now, we’re ready to call our colorChanged action when the user selects a color in the ChooseColorPage. This is the updated ChooseColorPage.js file:

Note that we have made three changes:

  • Imported the colorChanged action at the top
  • Connected it with connect() and mapStateToProps
  • Used it inside onSelectColor(colorName)

At this stage, we can refresh the simulator and run. If we choose a different color, the background color of the MainPage still doesn’t change.

This is because we haven’t told MainPage to use the new state.

Easy to fix. Open MainPage.js and add the required code:

A few notes:

  • mapStateToPropsnow sets the colorName from the state in the ColorReducer
  • This is then accessible via the props object and can be used inside selectedColor()
  • Don’t forget to import { connect } from 'react-redux'; at the top

If we try the app again in the simulator, we are now able to change the background color. ?

Updated snapshot: GitHub Code Snapshot 4.

Bonus: Presenting the Color Selection Page Modally

When we tap the Choose Colorbutton in the MainPage, the ChooseColorPage slides in from the right. This is the default navigation animation inside StackNavigator.

What if we wanted to present the ChooseColorPage modally instead?

This is easily done by changing the configuration of our AppNavigator like so:

Note the addition of navigationOptions with a headerLeft: null property inside ChooseColor, and the mode: ‘modal’ parameter.

If we try this on the simulator, the ChooseColorPage now slides in from the bottom.

React Navigation is very customizable. I recommend spending some time reading the documentation for the project, to learn all the things you can do with it.

Wrap Up

We have learned how to:

  • Setup and use Expo to run a mobile app on the simulator
  • Build an app with two different pages and navigate between them with React Navigation
  • Use actions and reducers to modify state from a screen, and use it to update the UI on another

You can find the complete source code on GitHub here.

I also shared the project publicly on Expo here.

I hope you enjoyed this tutorial. A good next step from here is to look at the official React Navigation Examples, as well as the other tutorials from the community.

Comments and feedback are appreciated. ?

And if you ???, I may even do a step-by-step video tutorial. ?

Om mig: Jeg er en freelance iOS-udvikler, der jonglerer mellem kontraktarbejde, open source, sideprojekter og blogging.

Jeg er @ biz84 på Twitter. Du kan også se min GitHub-side. Feedback, tweets, sjove gifs, alle velkomne! Min favorit? Masser af ???. Åh, og chokoladekager.