在 React Native 应用程序中使用 Redux 简介

介绍

Redux是JavaScript应用程序的可预测状态容器,如果Redux对你来说是新鲜的,我们建议你看看(https://andsky.com/tech/tutorials/redux-redux-intro)。

在本文中,您将学习如何在 React Native 应用程序中使用 Redux 继续使用用户数据. 该应用程序是一个模糊的社交网络,具有HomeScreen显示连接的朋友数,以及FriendsScreen显示可能添加的朋友列表. 您将使用 Redux 在两个屏幕之间共享状态。

前提条件

要完成本教程,您将需要:

本教程是建立在涵盖在 如何使用 React 导航在 React Native 中的路由的主题。

本教程已通过 Node v14.7.0、npm v6.14.7、react v16.13.1、react-native v0.63.2、@react-navigation/native v5.7.3、@react-navigation/stack v5.9.0、redux v4.0.5 和 react-redux v7.2.1 进行验证。

步骤 1 – 设置项目并安装Redux

本教程将使用在 如何在 React Native 中使用 React Navigation 的路由中修改的代码版本。

1git clone https://github.com/do-community/MySocialNetwork.git

然后,导航到项目目录:

1cd MySocialNetwork

将 git branch 更改为redux-starter:

1git checkout redux-starter

接下来,安装项目依赖:

1npm install

然后在项目中安装reduxreact-redux库:

您的项目已设置,您的依赖已安装。

步骤2 - 创建一个减少器

要将 Redux 连接到你的应用程序,你需要创建一个 reducer 和一个 action

首先,你将创建一个朋友减少器. 减少器是一个纯粹的函数,它将以前的 state 和一个行动作为论点,并返回一个新的状态。

在项目的根级别创建FriendsReducer.js文件:

1nano FriendsReducer.js

添加以下代码:

 1[label FriendsReducer.js]
 2import { combineReducers } from 'redux';
 3
 4const INITIAL_STATE = {
 5  current: [],
 6  possible: [
 7    'Alice',
 8    'Bob',
 9    'Sammy',
10  ],
11};
12
13const friendsReducer = (state = INITIAL_STATE, action) => {
14  switch (action.type) {
15    default:
16      return state
17  }
18};
19
20export default combineReducers({
21  friends: friendsReducer
22});

在此文件中,您创建了一个INITIAL_STATE变量,并将可能的朋友添加到您的社交网络中,然后将friendsReducer导出为一个名为friends的属性。

有了你的减速器,你需要一个方法来添加朋友。

步骤三:创建行动

操作是JavaScript对象,它们代表了从您的应用程序发送数据到Redux商店的信息。

在本教程中,类型将是ADD_FRIEND,有效载荷将是你添加到当前朋友数组中的朋友数组索引。

在项目的根级别创建FriendsActions.js文件:

1nano FriendsActions.js

添加朋友:

1[label FriendsActions.js]
2export const addFriend = friendsIndex => (
3  {
4    type: 'ADD_FRIEND',
5    payload: friendsIndex,
6  }
7);

当用户点击一个朋友时,这个代码将从friends.possible数组中获取friendsIndex

点击FriendsReducer.js查看:

1nano FriendsReducer.js

添加添加朋友:

 1[label FriendsReducer.js]
 2// ...
 3
 4const friendsReducer = (state = INITIAL_STATE, action) => {
 5  switch (action.type) {
 6    case 'ADD_FRIEND':
 7      // Pulls current and possible out of previous state
 8      // We do not want to alter state directly in case
 9      // another action is altering it at the same time
10      const {
11        current,
12        possible,
13      } = state;
14
15      // Pull friend out of friends.possible
16      // Note that action.payload === friendIndex
17      const addedFriend = possible.splice(action.payload, 1);
18
19      // And put friend in friends.current
20      current.push(addedFriend);
21
22      // Finally, update the redux state
23      const newState = { current, possible };
24
25      return newState;
26
27    default:
28      return state
29  }
30};
31
32// ...

此代码将当前和可能的朋友从以前的状态中拉出来。 Array.splice() 将朋友从可能的朋友的数组中获取。

现在,你有一个减速器和一个行动,你需要将减速器应用到你的应用程序。

步骤 4 – 将 Reducer 添加到应用程序

您需要使用 React Redux 的供应商组件提供应用程序的朋友状态。

打开App.js:

1nano App.js

导入供应商,createStorefriendsReducer:

 1[label App.js]
 2import 'react-native-gesture-handler';
 3import React from 'react';
 4import { Provider } from 'react-redux';
 5import { createStore } from 'redux';
 6import { StyleSheet } from 'react-native';
 7import { NavigationContainer } from '@react-navigation/native';
 8import { createStackNavigator } from '@react-navigation/stack';
 9import friendsReducer from './FriendsReducer';
10import HomeScreen from './HomeScreen';
11import FriendsScreen from './FriendsScreen';
12
13// ...

添加并替换突出的代码为createStoreProvider:

 1[label App.js]
 2// ...
 3
 4const store = createStore(friendsReducer);
 5
 6class App extends React.Component {
 7  // ...
 8
 9  render() {
10    return (
11      <Provider store={store}>
12        <NavigationContainer>
13          <Stack.Navigator>
14            <Stack.Screen
15              name="Home"
16              component={HomeScreen}
17            />
18            <Stack.Screen
19              name="Friends"
20              component={FriendsScreen}
21            />
22          </Stack.Navigator>
23        </NavigationContainer>
24      </Provider>
25    )
26  }
27}

现在朋友可以在您的应用程序中访问,但您仍然需要将其添加到主屏朋友屏

步骤 5 – 将 Redux 添加到屏幕

在此步骤中,您将通过mapStateToProps功能将朋友访问到您的屏幕上。

让我们从HomeScreen.js开始,打开HomeScreen.js文件:

1nano HomeScreen.js

HomeScreen.js中添加和替换突出的代码行:

 1[label HomeScreen.js]
 2import React from 'react';
 3import { connect } from 'react-redux';
 4import { StyleSheet, Text, View, Button } from 'react-native';
 5
 6class HomeScreen extends React.Component {
 7  render() {
 8    return (
 9      <View style={styles.container}>
10        <Text>You have (undefined) friends.</Text>
11
12        <Button
13          title="Add some friends"
14          onPress={() =>
15            this.props.navigation.navigate('Friends')
16          }
17        />
18      </View>
19    );
20  }
21}
22
23const styles = StyleSheet.create({
24  container: {
25    flex: 1,
26    backgroundColor: '#fff',
27    alignItems: 'center',
28    justifyContent: 'center',
29  },
30});
31
32const mapStateToProps = (state) => {
33  const { friends } = state
34  return { friends }
35};
36
37export default connect(mapStateToProps)(HomeScreen);

此代码更改添加了react-redux,并为HomeScreen提供朋友

接下来,添加当前朋友的值(this.props.friends.current):

 1[label HomeScreen.js]
 2class HomeScreen extends React.Component {
 3  render() {
 4    return (
 5      <View style={styles.container}>
 6        <Text>You have { this.props.friends.current.length } friends.</Text>
 7
 8        <Button
 9          title="Add some friends"
10          onPress={() =>
11            this.props.navigation.navigate('Friends')
12          }
13        />
14      </View>
15    );
16  }
17}

您的主屏幕现在会显示当前朋友的数量,您现在可以转到朋友屏幕

打开FriendsScreen.js:

1nano FriendsScreen.js

FriendsScreen.js中添加和替换突出的代码行:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { connect } from 'react-redux';
 4import { StyleSheet, Text, View, Button } from 'react-native';
 5
 6class FriendsScreen extends React.Component {
 7  render() {
 8    return (
 9      <View style={styles.container}>
10        <Text>Add friends here!</Text>
11
12        <Button
13          title="Back to home"
14          onPress={() =>
15            this.props.navigation.navigate('Home')
16          }
17        />
18      </View>
19    );
20  }
21}
22
23const styles = StyleSheet.create({
24  container: {
25    flex: 1,
26    backgroundColor: '#fff',
27    alignItems: 'center',
28    justifyContent: 'center',
29  },
30});
31
32const mapStateToProps = (state) => {
33  const { friends } = state
34  return { friends }
35};
36
37export default connect(mapStateToProps)(FriendsScreen);

此代码更改添加了react-redux,并在FriendsScreen中提供了朋友

添加可能的朋友的值(props.friends.possible):

 1class FriendsScreen extends React.Component {
 2  render() {
 3    return (
 4      <View style={styles.container}>
 5        <Text>Add friends here!</Text>
 6
 7        {
 8          this.props.friends.possible.map((friend, index) => (
 9            <Button
10              key={ friend }
11              title={ `Add ${ friend }` }
12            />
13          ))
14        }
15
16        <Button
17          title="Back to home"
18          onPress={() =>
19            this.props.navigation.navigate('Home')
20          }
21        />
22      </View>
23    );
24  }
25}

现在,当你导航到朋友屏幕,你会看到从减速器的所有可能的朋友。

最后,在FriendsScreen.js中添加新的addFriend Redux 操作:

 1[label FriendsScreen.js]
 2import React from 'react';
 3import { connect } from 'react-redux';
 4import { bindActionCreators } from 'redux';
 5import { StyleSheet, Text, View, Button } from 'react-native';
 6import { addFriend } from './FriendsActions';
 7
 8class FriendsScreen extends React.Component {
 9  render() {
10    return (
11      <View style={styles.container}>
12        <Text>Add friends here!</Text>
13
14        {
15          this.props.friends.possible.map((friend, index) => (
16            <Button
17              key={ friend }
18              title={ `Add ${ friend }` }
19              onPress={() =>
20                this.props.addFriend(index)
21              }
22            />
23          ))
24        }
25
26        <Button
27          title="Back to home"
28          onPress={() =>
29            this.props.navigation.navigate('Home')
30          }
31        />
32      </View>
33    );
34  }
35}
36
37// ...
38
39const mapDispatchToProps = dispatch => (
40  bindActionCreators({
41    addFriend,
42  }, dispatch)
43);
44
45export default connect(mapStateToProps, mapDispatchToProps)(FriendsScreen);

让我们将两个朋友添加到社交网络,然后返回HomeScreen,看看用户目前有多少朋友:

A series of screenshots depicting the HomeScreen and FriendsScreen as a user adds two friends and the array of possible friends and count of current friends channges.

通过这种方式,您已经将所有的逻辑从App.js迁移到Redux,这使得您的应用程序更加灵活,特别是当您添加更多的页面和功能,如身份验证和数据库集成。

在我们打包之前,让我们清理代码。

步骤六:清理

现在你正在使用Redux,你将不再需要你从App.js传递的证书。

您可以通过将您的动作类型存储在一个单独的文件中来进一步清理。

你在两个地方使用ADD_FRIEND字符串:在action字符串和reducer字符串。这很危险,因为如果你在一个地方更改字符串,而不是另一个地方,你可以打破你的应用程序。

在根级别创建types.js文件:

1nano types.js

添加以下代码:

1[label types.js]
2export const ADD_FRIEND = 'ADD_FRIEND';

然后,重定向FriendsActions.js以使用新的ADD_FRIEND:

1nano FriendsActions.js

在你的动作中,将引用ADD_FRIEND更改为ADD_FRIEND变量:

1[label FriendsActions.js]
2import { ADD_FRIEND } from './types';
3
4export const addFriend = friendsIndex => (
5  {
6    type: ADD_FRIEND,
7    payload: friendsIndex,
8  }
9);

然后,重新参阅FriendsReducer.js以使用新的ADD_FRIEND:

1nano FriendsReducer.js

在您的减速器中,将引用ADD_FRIEND更改为ADD_FRIEND变量:

 1[label FriendsReducer.js]
 2import { combineReducers } from 'redux';
 3import { ADD_FRIEND } from './types';
 4
 5// ...
 6
 7const friendsReducer = (state = INITIAL_STATE, action) => {
 8  switch (action.type) {
 9    case ADD_FRIEND:
10      // ...
11
12    default:
13      return state;
14  }
15};

在开发应用程序时,你应该意识到巩固代码的机会,避免重复自己。

结论

在本教程中,您涵盖了减少,减少,行动和可扩展的数据管理。

您可以使用 Redux 做更多事情,从保持数据与数据库同步到身份验证和跟踪用户权限。

完整的 本教程的源代码在GitHub上可用

如果您想了解更多关于 React 的信息,请查看我们的 如何在 React.js 中编码系列,或查看 我们的 React 主题页面以获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus