React中Redux的基本用法
Redux是React中使用较多的状态管理库,这篇文章主要介绍了Redux的基本用法,快来看看吧
首先我们需要新建一个React项目,我使用的React+TS,文件结构如下
Redux的相关使用主要在store文件中
- Store:存储整个应用的状态
- Action:一个描述发生了什么的JS对象
- Reducer:一个纯函数,根据传入的action更新相关的状态
- Dispatch:发送action到reducer的方法
- Selector:从Store中获取函数的函数
接下来,需要安装相关的包
npm install redux react-redux
之后,我们在相关文件中写相关的规范
- types.ts
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
- action.ts
import { INCREMENT, DECREMENT } from './types';export const increment = () => ({type: INCREMENT,
});export const decrement = () => ({type: DECREMENT,
});
- reducers.ts
import { INCREMENT, DECREMENT } from './types';const initialState = {count: 0,
};const counterReducer = (state = initialState, action) => {switch (action.type) {case INCREMENT:return { ...state, count: state.count + 1 };case DECREMENT:return { ...state, count: state.count - 1 };default:return state;}
};export default counterReducer;
- index.js
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import counterReducer from './reducers';const store = createStore(counterReducer, composeWithDevTools());export default store;
之后,我们需要将store提供给React应用来使用,在main.tsx中,进行如下修改
// import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import store from './store/index.ts'
import { Provider } from 'react-redux'createRoot(document.getElementById('root')!).render(// <StrictMode><Provider store={store}><App /></Provider>// </StrictMode>,
)
这样做的目的是,将 Redux Store 注入到整个 React 应用中,这样子组件都可以通过 useSelector 和 useDispatch 访问 Store
接下来,就是在组件中进行使用了,在我们的App.tsx文件中,将相关的方法进行引用
import './App.css'
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './store/action';function App() {// 使用 useSelector 从 Redux Store 获取数据const count = useSelector((state) => state.count);// 使用 useDispatch 发送 actionconst dispatch = useDispatch();return (<><div><h2>Count: {count}</h2><button onClick={() => dispatch(increment())}>Increment</button><button onClick={() => dispatch(decrement())}>Decrement</button></div></>)
}export default App
useSelector() 可以从 Store 中选择数据,然后调用useDispatch() 返回 dispatch 方法,可以触发相关的action,这样就可以成功使用Redux了
但是,在实际开发中,我们大多数情况下都是会处理异步的情况,那么在Redux中如何使用异步呢?由于Redux本身只支持同步数据流,如果处理异步操作,我们需要使用React Thunk中间件
首先需要在store文件夹下边index.ts文件中进行如下修改
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import counterReducer from './reducers';const store = createStore(counterReducer,composeWithDevTools(applyMiddleware(thunk))
);export default store;
接下来就可以在action.ts文件中封装相关的异步操作,案例如下
export const fetchData = () => {return async (dispatch) => {try {const response = await fetch('www.baidu.com');const res = await response.json();dispatch({ type: 'FETCH_SUCCESS', payload: data });} catch (error) {dispatch({ type: 'FETCH_ERROR', payload: error });}};
};
最后在reducers.ts中进行数据返回即可
const initialState = {count: 0,data: null,error: null,
};const counterReducer = (state = initialState, action) => {switch (action.type) {case 'FETCH_SUCCESS':return { ...state, data: action.payload };case 'FETCH_ERROR':return { ...state, error: action.payload };default:return state;}
};export default counterReducer;
以上便是Redux的基本操作,希望可以帮助到你