WHAT YOU’LL LEARN
- How to add “slices” of reducer logic to the Redux store with
createSlice
- Reading Redux data in components with the
useSelector
hook- Dispatching actions in components with the
useDispatch
hook我们将学到什么
- 如何通过createSlice增加reducer逻辑的“slices”到Redux store
- 使用useSelector钩子读取组件中的Redux数据
- 使用useDispatch钩子发送组件中的actions
PREREQUISITES
- Familiarity with key Redux terms and concepts like “actions”, “reducers”, “store”, and “dispatching”. (See Part 1 for explanations of these terms.)
前提条件
- 熟悉关键Redux语法和概念,比如“actions”,“reducers”,“store”和“dispatching”。(看part1这些语法的解释)
Introduction
In Part 1: Redux Overview and Concepts, we looked at how Redux can help us build maintainable apps by giving us a single central place to put global app state. We also talked about core Redux concepts like dispatching action objects, using reducer functions that return new state values, and writing async logic using thunks. In Part 2: Redux App Structure, we saw how APIs like configureStore and createSlice from Redux Toolkit and Provider and useSelector from React-Redux work together to let us write Redux logic and interact with that logic from our React components.
第一部分:Redux概述和概念,我们看了Redux可以帮助我们创建可维护的应用程序,通过给我们一个放置全局状态的单独的中央位置。我们也讨论了Redux的新概念比如派发action对象,用reducer函数返回一个新的state值,用thunks编写异步逻辑。
第二部分:Redux程序结构,我们看了Redux Toolkit 的API像congfigureStore和createSlice和React-Redux的Provider和useSelector工作在一起,让我们编写Redux逻辑,并通过React组件与该逻辑进项交互。
Now that you have some idea of what these pieces are, it’s time to put that knowledge into practice. We’re going to build a small social media feed app, which will include a number of features that demonstrate some real-world use cases. This will help you understand how to use Redux in your own applications.
现在你已经了解这部分是什么,是时候运用这些知识到实践中。我们继续构建一个小的社交媒体feed app,
其中将包含许多功能,这些功能将演示一些实际的用例。这将帮助你明白如何使用Redux在你的应用程序中。
CAUTION
The example app is not meant as a complete production-ready project. The goal is to help you learn the Redux APIs and typical usage patterns, and point you in the right direction using some limited examples. Also, some of the early pieces we build will be updated later on to show better ways to do things. Please read through the whole tutorial to see all the concepts in use.
警告 案例程序不是意味着一个完整的生产就绪项目。目的是帮助你学习Redux API和典型的使用模式,和使用一些有限的案例指明正确的方向。同时,我们早前创建的片段稍后被更新,展示更好的方式做事。请阅读整个教程去看所有正在使用的概念。
Project Setup
For this tutorial, we’ve created a pre-configured starter project that already has React and Redux set up, includes some default styling, and has a fake REST API that will allow us to write actual API requests in our app. You’ll use this as the basis for writing the actual application code.
在本教程中,我们已经创建包含React和Redux设置的预配置初始项目,包含一些默认样式,并伪造了假的的REST API,那可以帮助我们在应用程序中编写实际的API请求。你将用这些作为基础来编写实际的应用程序代码。
To get started, you can open and fork this CodeSandbox:
开始,你可以打开并派生这个代码沙盒
You can also clone the same project from this Github repo. After cloning the repo, you can install the tools for the project with npm install, and start it with npm start.
你也可以从Github仓库克隆同样的项目。克隆完仓库,你可以用npm install安装这个项目的工具,使用npm start开启项目。**
If you’d like to see the final version of what we’re going to build, you can check out the tutorial-steps branch, or look at the final version in this CodeSandbox.
如果你想查看我们要构建的最终版本,你可以查看教程步骤节点,或者在代码沙盒看最终版本。
**
We’d like to thank Tania Rascia, whose Using Redux with React tutorial helped inspire the example in this page. It also uses her Primitive UI CSS starter for styling.
我们想要感谢Tania Rascia,通过React使用Redux教程帮助启发此页面的案例。它也用她的原始UI CSS入门作为样式。
Creating a New Redux + React Project
Once you’ve finished this tutorial, you’ll probably want to try working on your own projects. We recommend using the Redux templates for Create-React-App as the fastest way to create a new Redux + React project. It comes with Redux Toolkit and React-Redux already configured, using the same “counter” app example you saw in Part 1. This lets you jump right into writing your actual application code without having to add the Redux packages and set up the store.
完成本教程后,你多半想要尝试在你的项目中。我们推荐使用Redux templates for Create-React-App最为最快的方式常见一个新的Redux+React项目。它带有Redux Toolkit和已经配置的React-Redux。使用你过的第一部分的相同的计数器应用案例。这让你直接编写你的实际应用程序代码,而不用不得不增加Redux包和配置store。
If you want to know specific details on how to add Redux to a project, see this explanation:
如果你想要知道如何增加Redux到项目中的具体细节,看这个说明:
暂时省略,有时间在更新…
Exploring the Initial Project
探索初始项目
Let’s take a quick look at what the initial project contains:
让我们快速看看初始项目包含的内容:
If you load the app now, you should see the header and a welcome message. We can also open up the Redux DevTools Extension and see that our initial Redux state is entirely empty.
如果你现在加载应用程序,你应该看header和欢迎信息。我们也能打开Redux开发者拓展工具并看到初始化Redux状态是完全为空。
With that, let’s get started!
这样,我们开始吧!
Main Posts Feed
The main feature for our social media feed app will be a list of posts. We’ll add several more pieces to this feature as we go along, but to start off, our first goal is to only show the list of post entries on screen.
我们社会化媒体Feed应用程序的主要功能是帖子列表。我们将继续增加一些更多的片段给这个功能,但是要开始,我们第一个目标是在屏幕上展示帖子条目列表。
Creating the Posts Slice
The first step is to create a new Redux “slice” that will contain the data for our posts. Once we have that data in the Redux store, we can create the React components to show that data on the page.
第一步是创建一个新的Redux “切片”,它包含帖子数据的。一旦 我们在Redux store里有那些数据,我们能创建React组件用来在网页上展示数据。
Inside of src, create a new features folder, put a posts folder inside of features, and add a new file named postsSlice.js.
在src目录中,创建一个新的功能文件夹,把posts文件夹放在features文件夹里面,并增加一个新的文件,命名为postsSlice.js。
We’re going to use the Redux Toolkit createSlice function to make a reducer function that knows how to handle our posts data. Reducer functions need to have some initial data included so that the Redux store has those values loaded when the app starts up.
我们将使用Redux Toolkit 提供的createSlice函数创建一个reducer函数,它知道如何去处理我们的帖子数据。Reducer函数需要去包含一些初始数据,以便应用程序启动时Redux store加载这些值。
For now, we’ll create an array with some fake post objects inside so that we can begin adding the UI.
现在,我们用一些虚拟的帖子对象创建一个数组,以便我们可以开始增加UI。
We’ll import createSlice, define our initial posts array, pass that to createSlice, and export the posts reducer function that createSlice generated for us:
我们引入createSlice,定义我们的初始帖子数组,传递数组给createSlice,然后导出帖子createSlice生成的reducer函数:
features/posts/postsSlice.js
import { createSlice } from '@reduxjs/toolkit'
const initialState = [
{ id: '1', title: 'First Post!', content: 'Hello!' },
{ id: '2', title: 'Second Post', content: 'More text' }
]
const postsSlice = createSlice({
name: 'posts',
initialState,
reducers: {}
})
export default postsSlice.reducer
Every time we create a new slice, we need to add its reducer function to our Redux store. We already have a Redux store being created, but right now it doesn’t have any data inside. Open upapp/store.js
, import the postsReducer
function, and update the call to configureStore
so that the postsReducer
is being passed as a reducer field named posts
:
每当我们创建一个新的slice,我们需要增加他的reducer函数到我们的Redux store。我们已经有一个创建好的Redux store,但是现在它没有任何数据。打开app/store.js, 引入postsReducer 函数,并调用configureStore,以便传入postsReducer 作为reducer 的作用域,命名为posts:
app/store.js
import { configureStore } from '@reduxjs/toolkit'
import postsReducer from '../features/posts/postsSlice'
export default configureStore({
reducer: {
posts: postsReducer
}
})
This tells Redux that we want our top-level state object to have a field named posts inside, and all the data for state.posts
will be updated by the postsReducer function when actions are dispatched.
告诉Redux我们想要我们的高水平状态对象去有一个名叫posts的域在里面,并且当派发actions时,所有state.post
的数据通过postsReducer函数更新。
We can confirm that this works by opening the Redux DevTools Extension and looking at the current state contents:
我们可以通过打开Redux DevTools Extension和看当前状态内容来确实方法有效。
Showing the Posts List
Now that we have some posts data in our store, we can create a React component that shows the list of posts. All of the code related to our feed posts feature should go in the posts
folder, so go ahead and create a new file named PostsList.js
in there.
现在我们有一些帖子数据在store中,我们能创建一个React 组件来展示帖子列表。所有我们feed posts 功能有关的代码应该放到posts文件夹,所有在这里继续创建一个命名为PostList.js
的文件。
If we’re going to render a list of posts, we need to get the data from somewhere. React components can read data from the Redux store using the useSelector hook from the React-Redux library. The “selector functions” that you write will be called with the entire Redux state object as a parameter, and should return the specific data that this component needs from the store.
未完待续…