使用Redux在React Navigation App中管理状态

松霖
2023-12-01

by Andrea Bizzotto

通过安德里亚·比佐托(Andrea Bizzotto)

使用Redux在React Navigation App中管理状态 (Managing State in a React Navigation App with Redux)

In this tutorial, I will show how to manage navigation and application state by building a simple app with React Navigation and Redux.

在本教程中,我将展示如何通过使用React NavigationRedux构建一个简单的应用程序来管理导航应用程序状态

Prerequisite: you should already be familiar with React Native, React Navigation, and Redux. If you’re just getting started with React Native, I highly recommend this course:

先决条件 :您应该已经熟悉React Native,React Navigation和Redux。 如果您刚开始使用React Native,我强烈建议您学习以下课程:

应用概述 (Application Overview)

We’re going to build an app made of two pages:

我们将构建一个由两个页面组成的应用程序:

  • Main Page: This shows a container view with a specific background color, and a button. When the button is pressed, the second page is presented.

    主页面 :显示具有特定背景颜色的容器视图和一个按钮。 按下按钮后,将显示第二页。

  • Choose Color Page: This shows RED, GREEN and BLUE buttons. When a color is selected, the app returns to the main page and shows the updated background color.

    选择彩色页 :显示红色,绿色和蓝色按钮。 选择颜色后,应用程序将返回主页并显示更新的背景色。

By building this app, you will learn:

通过构建此应用程序,您将学到:

  • How to navigate between different screens with React Navigation

    如何使用React Navigation在不同屏幕之间导航

  • How to use reducers and actions to update application state, so that actions on one screen drive UI changes on another

    如何使用reducer和操作更新应用程序状态,以便一个屏幕驱动器UI上的操作在另一个屏幕上更改

With this knowledge, you’ll be able to build more complex apps.

有了这些知识,您就可以构建更复杂的应用程序。

Note: For the remainder of this tutorial, I will use the terms “page” and “screen” to mean the same thing.

注意:在本教程的其余部分中,我将使用术语“页面”和“屏幕”来表示相同的内容。

项目设置(展览) (Project Setup (Expo))

We’re going to build this app with the Expo XDE.

我们将使用Expo XDE构建此应用程序。

You can download Expo for your OS from the Expo XDE GitHub page.

您可以从Expo XDE GitHub页面下载适用于您的操作系统的Expo

Then head over to the installation instructions on the Expo Docs. These will show you how to install the XDE on your desktop, and run apps within Expo on simulator/device.

然后转到Expo Docs上的安装说明 。 这些将向您展示如何在桌面上安装XDE,以及如何在模拟器/设备上的Expo中运行应用程序。

As we’ll be running the app on the simulator, you’ll also need to download Xcode or Android Studio.

由于我们将在模拟器上运行该应用程序,因此您还需要下载XcodeAndroid Studio

Upon launching Expo, this page is presented:

启动世博会后,将显示以下页面:

  • Select “Create new project…”

    选择“创建新项目…”
  • Choose the blank template, and name the project redux-navigation

    选择空白模板,然后将项目命名为redux-navigation

The project will be created, then the React Native packager will start.

将创建项目,然后将启动React Native打包程序。

To run the app in the simulator, select Device -> Open in iOS Simulator.

要在模拟器中运行该应用,请选择设备->在iOS Simula tor中打开

Once the simulator is booted up, the following screen appears:

模拟器启动后,将显示以下屏幕:

As the project is now created, it can be opened with your editor of choice. I use Visual Studio Code with the React Native Tools extension.

现在创建了项目,可以使用您选择的编辑器打开它。 我将Visual Studio CodeReact Native Tools扩展一起使用

构建应用 (Building the app)

Before we can code our app, we need to install all the dependencies it needs.

在编写应用程序代码之前,我们需要安装其所需的所有依赖项。

Open a terminal, move to the project folder you created in Expo, and type:

打开一个终端,移至在Expo中创建的项目文件夹,然后键入:

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

Then, make sure to hit the Restart button in Expo. If you don’t do this, the new dependencies won’t be recognized and the simulator will throw a red error screen if you try to use them.

然后, 确保点击Expo中的Restart按钮 。 如果不这样做,则新的依赖项将不会被识别,如果您尝试使用它们,模拟器将显示红色错误屏幕。

Time to build our app. I organized my project folders like this:

是时候构建我们​​的应用程序了。 我这样组织我的项目文件夹:

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

You can replicate this same structure from your 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 ..

Copy-paste the following code into the Colors.js file:

将以下代码复制粘贴到Colors.js文件中:

Next, create the MainPage with a default background color and a button:

接下来,使用默认背景色和一个按钮创建MainPage

A few notes:

一些注意事项:

  • MainPage is a React component rather than a stateless functional component, because it will need to access application state

    MainPage是React组件,而不是无状态功能组件 ,因为它将需要访问应用程序状态

  • I use flex: 1, alignSelf: 'stretch' to make the container view extend to the whole screen

    我使用flex: 1, alignSelf: 'stretch'使容器视图扩展到整个屏幕

  • The color of the container view is defined in the selectedColor() method, which samples RED from our COLORS table, and returns the corresponding hex code

    容器视图的颜色在selectedColor()方法中定义,该方法从我们的COLORS表中采样RED ,并返回相应的十六进制代码

  • I have added an empty onChooseColor() handler for the button press event. We will add the body of this method later.

    我为按钮按下事件添加了一个空的onChooseColor()处理函数。 我们稍后将添加此方法的主体。

Time to hook up our MainPage into our root App.js file. Replace the old contents with this:

是时候将MainPage到我们的根App.js文件了。 用以下内容替换旧内容:

Refreshing the simulator yields this:

刷新模拟器会产生以下结果:

Not pretty, but it shows the background color and our button as intended.

不漂亮,但是它显示了预期的背景颜色和我们的按钮。

Here is a snapshot of what we’ve built so far: GitHub Code Snapshot 1.

这是到目前为止我们构建的快照GitHub Code Snapshot 1

添加导航 (Adding Navigation)

We are now ready to add some navigation to our app.

现在,我们准备向我们的应用添加一些导航。

To do this, open the AppNavigator.js file and add these contents:

为此,请打开AppNavigator.js文件并添加以下内容:

This code is borrowed from the Redux Example in the react-navigation project.

此代码是从react-navigation项目中的Redux Example中借用的。

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

它使用MainPage作为其主屏幕来定义一个StackNavigator

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.

它还设置AppWithNavigationState ,这是保存导航状态的顶级容器。 如果不清楚,请放心。 这是React Navigation中的标准样板代码,我们现在仅使用它即可开始工作。

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:

是时候编写Navigation Reducer了,它将保留Redux存储内的导航状态。 打开NavReducer.js文件并添加以下内容:

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

该reducer定义了我们应用的初始导航状态。 再次,样板代码。

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

现在,让我们打开AppReducer.js文件并添加以下内容:

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

随着应用程序的增长,除了NavReducer ,我们可能还需要其他减速器。 因此,我们可以将它们全部合并到AppReducer

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

最后,我们能够更新App.js以使用所有这些新功能:

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.

render方法返回具有创建的redux存储的提供程序,并保存我们的顶级组件。 同样,这只是将代码与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.

完成所有这些代码后,如果缺少任何内容,您可能会在模拟器上遇到一些错误。 如果是这样,请使用此代码快照使之回到正轨: 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.

现在,我们在StackNavigator有了MainPage ,我们准备添加ChooseColorPage以便我们可以导航到它。

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

打开ChooseColorPage.js文件并添加以下代码:

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.

    render()方法中的代码遍历每种颜色,并将其映射到Button 。 设置titlecolor属性。

  • When the button is tapped, the onSelectColor() handler is called with the appropriate color key.

    轻按按钮时,将使用适当的颜色键调用onSelectColor()处理程序。

  • The navigation object is accessible via props. In fact, it is injected into all the screens in our AppNavigator.

    可以通过props访问navigation对象。 实际上,它已注入到AppNavigator所有屏幕中。

  • Calling this.props.navigation.goBack() takes us back to the previous screen in the AppNavigator.

    调用this.props.navigation.goBack()把我们带回到在上一屏幕AppNavigator

  • At this stage, colorName is not yet used to set any state.

    在此阶段, colorName尚未用于设置任何状态。

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

接下来,我们必须使AppNavigator意识到新的ChooseColorPage屏幕。 让我们在AppNavigator.js文件中对其进行更新:

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

最后,在MainPage上点击“ Choose Color按钮时,添加代码以导航至ChooseColorPage

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

如果我们现在刷新模拟器并点击“ Choose Color ,则应用程序将导航到新屏幕,其中显示三个按钮:

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

注意:调用navigation.navigate('ChooseColor')之所以有效,是因为我们已将ChooseColor命名为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.

再说一次,如果有些事情不起作用,您可以将保存的代码快照保存到这一点: GitHub Code Snapshot 3

管理应用程序状态 (Managing application state)

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

我们将使用Redux将MainPage的背景色设置为应用程序状态。

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

为此,我们需要定义一个“变色”操作和一个“减色剂”。

Open the ColorChangedAction.js file and add the following:

打开ColorChangedAction.js文件并添加以下内容:

Then, open ColorReducer.js add add this:

然后,打开ColorReducer.js添加以下内容:

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

为了使用此减速器,我们需要将其添加到AppReducer.js如下所示:

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:

现在,当用户在ChooseColorPage选择一种颜色时,我们准备调用colorChanged动作。 这是更新的ChooseColorPage.js文件:

Note that we have made three changes:

请注意,我们进行了三处更改:

  • Imported the colorChanged action at the top

    在顶部导入了colorChanged操作

  • Connected it with connect() and mapStateToProps

    将其与connect()mapStateToProps connect()

  • Used it inside onSelectColor(colorName)

    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.

在这一阶段,我们可以刷新模拟器并运行。 如果我们选择其他颜色,则MainPage的背景颜色仍然不会改变。

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

这是因为我们没有告诉MainPage使用新状态。

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

易于修复。 打开MainPage.js并添加所需的代码:

A few notes:

一些注意事项:

  • mapStateToProps now sets the colorName from the state in the ColorReducer

    mapStateToProps现在设置colorName从国家ColorReducer

  • This is then accessible via the props object and can be used inside selectedColor()

    然后可以通过props对象访问它,并且可以在selectedColor()内部使用

  • Don’t forget to import { connect } from 'react-redux'; at the top

    不要忘记import { connect } from 'react-redux'; 在顶部

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

现在,如果我们在模拟器中再次尝试该应用程序,则可以更改背景色。 ?

Updated snapshot: GitHub Code Snapshot 4.

更新的快照: GitHub代码快照4

奖励:以模态呈现颜色选择页面 (Bonus: Presenting the Color Selection Page Modally)

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

当我们点击MainPageChoose Color按钮时, ChooseColorPage从右侧滑入。 这是StackNavigator的默认导航动画。

What if we wanted to present the ChooseColorPage modally instead?

如果我们想以模态方式呈现ChooseColorPage怎么办?

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

可以通过如下更改AppNavigator的配置轻松完成此操作:

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

请注意,在ChooseColor添加了带有headerLeft: null属性的navigationOptions ,以及mode: 'modal'参数。

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

如果我们在模拟器上尝试此操作,那么ChooseColorPage现在将从底部滑入。

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.

React Navigation是非常可定制的。 我建议花一些时间阅读该项目的文档,以学习使用该项目可以做的所有事情。

结语 (Wrap Up)

We have learned how to:

我们已经学会了如何:

  • Setup and use Expo to run a mobile app on the simulator

    设置并使用Expo在模拟器上运行移动应用
  • Build an app with two different pages and navigate between them with React Navigation

    使用两个不同的页面构建一个应用程序,并使用React Navigation在它们之间进行导航
  • Use actions and reducers to modify state from a screen, and use it to update the UI on another

    使用动作和化简来修改屏幕上的状态,并使用它来更新另一个屏幕上的UI

You can find the complete source code on GitHub here.

您可以在GitHub上找到完整的源代码。

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.

我希望您喜欢本教程。 从这里开始的一个很好的下一步是查看官方的React Navigation Example ,以及社区中的其他教程

Comments and feedback are appreciated. ?

评论和反馈表示赞赏。 ?

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

如果您???,我什至可以做一个逐步的视频教程。 ?

About me: I’m a freelance iOS developer, juggling between contract work, open source, side projects and blogging.

关于我:我是一名自由职业的iOS开发人员,在合同工作,开源,副项目和博客之间徘徊。

I’m @biz84 on Twitter. You can also see my GitHub page. Feedback, tweets, funny gifs, all welcome! My favourite? Lots of ???. Oh, and chocolate cookies.

我在Twitter上为@ biz84 。 您还可以看到我的GitHub页面。 反馈,推文,有趣的GIF,欢迎您! 我的最爱? 很多 ???。 哦,还有巧克力饼干。

翻译自: https://www.freecodecamp.org/news/managing-state-in-a-react-navigation-app-with-redux-6d0b680fb595/

 类似资料: