【React进阶】什么是Redux?

94 阅读2分钟

Redux 是一个状态管理库,它可以帮助我们管理 React 应用中的状态。下面是 Redux 的详细用法及案例说明:

  1. 安装 Redux
npm install redux
  1. 创建 store
import { createStore } from 'redux';

const initialState = { count: 0 };

function reducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

const store = createStore(reducer);

在上面的代码中,我们创建了一个 store,并传入了一个 reducer 函数。reducer 函数接收两个参数:当前状态和 action,根据 action 的类型来更新状态。我们还定义了一个初始状态 initialState,它包含一个 count 属性,初始值为 0。

  1. 在组件中使用 store
import { useSelector, useDispatch } from 'react-redux';

function Counter() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <div>{count}</div>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
}

在上面的代码中,我们使用了两个 React Redux 提供的 Hook:useSelectoruseDispatch

useSelector 接收一个函数作为参数,这个函数会接收整个 store 的状态,并返回需要的部分。在上面的例子中,我们只需要 count 属性,所以返回 state.count。

useDispatch 返回一个 dispatch 函数,我们可以用它来派发 action,从而更新 store 中的状态。

  1. 使用 Provider

在使用 Redux 的时候,我们需要把 store 提供给整个应用。这可以通过 React Redux 提供的 Provider 组件来实现:

import { Provider } from 'react-redux';

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

在上面的代码中,我们把 store 作为 Provider 组件的属性传递给了整个应用。这样,我们就可以在任何组件中使用 Redux 了。

  1. 异步操作

在实际开发中,我们经常需要进行异步操作,比如从服务器获取数据。Redux 提供了一些中间件来处理异步操作,最常用的是 redux-thunk。

npm install redux-thunk
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';

const store = createStore(reducer, applyMiddleware(thunk));

在上面的代码中,我们使用 applyMiddleware 函数来应用中间件。thunk 中间件允许我们 dispatch 函数而不是对象,这样我们就可以进行异步操作了:

function fetchData() {
  return dispatch => {
    dispatch({ type: 'FETCH_START' });
    fetch('/api/data')
      .then(response => response.json())
      .then(data => {
        dispatch({ type: 'FETCH_SUCCESS', payload: data });
      })
      .catch(error => {
        dispatch({ type: 'FETCH_ERROR', payload: error });
      });
  };
}

在上面的代码中,fetchData 函数返回一个函数,这个函数接收 dispatch 函数作为参数。在这个函数中,我们首先 dispatch 一个 FETCH_START 的 action,表示开始获取数据。然后使用 fetch 函数获取数据,并根据结果 dispatch 不同的 action。