0Pricing
React Native Academy · 课时

设置 Redux 存储与 Provider

安装 @reduxjs/toolkit 和 react-redux,使用 configureStore 配置存储,并将应用包裹在 Provider 中,使存储全局可用。

设置 Redux 存储与 Provider 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is Redux Toolkit?

Redux Toolkit (RTK) is the official, recommended way to write Redux logic today. It eliminates the boilerplate of classic Redux by providing utility functions like configureStore, createSlice, and createAsyncThunk. RTK includes best practices by default, such as Immer for immutable updates and Redux DevTools integration.

Installing the Required Packages

To get started with Redux Toolkit in React Native, you need two packages: @reduxjs/toolkit provides the core utilities, and react-redux provides the React bindings. Install them with a single command and they are ready to use immediately.

npm install @reduxjs/toolkit react-redux

Configuring the Store

The store is the single source of truth for your entire Redux application state. You create it with configureStore, passing a reducer object that maps slice names to their reducer functions. RTK automatically sets up Redux DevTools and applies recommended middleware like redux-thunk.

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

Wrapping the App with Provider

The Provider component from react-redux makes the Redux store available to every component in your React Native component tree. Wrap your root component (or NavigationContainer if using React Navigation) with <Provider store={store}>. Any component inside the tree can then access the store using hooks.

import React from 'react';
import { Provider } from 'react-redux';
import { store } from './store';
import AppNavigator from './navigation/AppNavigator';

export default function App() {
  return (
    <Provider store={store}>
      <AppNavigator />
    </Provider>
  );
}

Understanding the Redux Data Flow

Redux enforces a strict unidirectional data flow: the UI dispatches an action, the reducer processes that action to produce a new state, the store saves the new state, and the UI re-renders to reflect the change. This predictable cycle makes debugging and testing straightforward, because every state change is traceable to a specific action.

TypeScript Typed Hooks

In TypeScript projects it is best practice to create typed versions of useDispatch and useSelector so you get autocompletion and type safety throughout the app. Export useAppDispatch and useAppSelector from a hooks file and import them in your components instead of the raw hooks.

import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector = <T>(selector: (state: RootState) => T): T =>
  useSelector(selector);

The Reducer Object in configureStore

The reducer key inside configureStore accepts an object where each key becomes a slice name in the global state. For example, passing { counter: counterReducer, user: userReducer } means your state shape is { counter: {...}, user: {...} }. You can add more slices at any time without changing existing slices.

export const store = configureStore({
  reducer: {
    counter: counterReducer,
    user: userReducer,
    products: productsReducer,
  },
});

Redux DevTools Integration

configureStore automatically enables the Redux DevTools browser extension in development mode. With DevTools you can inspect the current state, view every dispatched action, and even time-travel back to a previous state snapshot. This is one of the biggest debugging advantages of using Redux over plain useState.

Default Middleware in Redux Toolkit

RTK's configureStore adds several middleware by default: redux-thunk for async action creators, serializability check middleware that warns when non-serializable values (like functions or class instances) are placed in state, and an immutability check that warns if state is mutated directly. You can customize this with the middleware option.

import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';

export const store = configureStore({
  reducer: { counter: counterReducer },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

Organizing the Store Folder

A clean folder structure makes Redux apps maintainable. The common pattern is a store/ folder with an index.ts for the store configuration and a features/ subfolder where each feature has its own slice file. For example: store/features/counter/counterSlice.ts. Keep slice files small and focused on a single domain concept.

src/
  store/
    index.ts          // configureStore + exports
    hooks.ts          // useAppDispatch, useAppSelector
    features/
      counter/
        counterSlice.ts
      user/
        userSlice.ts

Verifying the Store Is Connected

A quick sanity check after wiring up the Provider is to log store.getState() in the store file. This prints the initial state to the console and confirms the reducer map is correctly structured. Once you see the expected shape — for example { counter: { value: 0 } } — you know the store is ready for components to read from and write to.

import { store } from './store';
console.log('Initial state:', store.getState());
// Output: { counter: { value: 0 }, user: { name: null } }

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: Redux Toolkit reduces boilerplate with configureStore and built-in middleware, the Provider component makes the store accessible to the entire component tree, and typed hooks (useAppDispatch, useAppSelector) add TypeScript safety to your Redux code. Next up we explore creating slices with createSlice.

常见问题解答

「设置 Redux 存储与 Provider」课时是免费的吗?

是的 — 「设置 Redux 存储与 Provider」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「设置 Redux 存储与 Provider」这节课中我会学到什么?

安装 @reduxjs/toolkit 和 react-redux,使用 configureStore 配置存储,并将应用包裹在 Provider 中,使存储全局可用。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「设置 Redux 存储与 Provider」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置 Redux 存储与 Provider
  2. 使用 createSlice 创建切片
  3. 使用 useSelector 读取状态
  4. 使用 createAsyncThunk 处理异步任务
← 返回 React Native Academy