博客
关于我
react redux使用
阅读量:376 次
发布时间:2019-03-05

本文共 2233 字,大约阅读时间需要 7 分钟。

Redux 基本使用与进阶优化

一、 Redux 基本使用

1. 创建项目

安装必要工具:

npm install -g create-react-app

创建项目:

create-react-app react-redux-ant

2. 安装 Redux

通过Yarn安装:

yarn add redux --save

3. 创建 Redux 存储

src 目录下创建 storereducers 目录:

  • store/index.js
import { createStore } from 'redux';import reducer from './reducers/reducer';const store = createStore(reducer);export default store;
  • reducers/reducer.js
const defaultState = {  number: 0,  userInfo: { name: 'wxq' }};export default (state = defaultState, action) => {  return state;};

4. 使用 Redux 数据

在组件中使用:

const { number } = props.store.getState();

5. 修改 Redux 状态

通过 dispatch 方法:

props.store.dispatch({  type: 'ADD',  data: 1});

6. 状态更新处理

在组件中:

const add = () => {  props.store.dispatch({    type: 'ADD',    data: 1  });};

二、 Redux 进阶优化

1. 模块化 reducers

创建 reducers.js

import { combineReducers } from 'redux';import counter from './counter/index';const reducers = combineReducers({  counter});export default reducers;

2. 使用 React-Redux

安装 React-Redux:

yarn add react-redux

3. Provider 组件

在主组件外使用 Provider

import React from 'react';import ReactDOM from 'react-dom';import App from './App';import store from './store';import { Provider } from 'react-redux';ReactDOM.render(  
, document.getElementById('root'));

4. 容器组件

在组件外部使用 connect

import React from 'react';import { connect } from 'react-redux';const Index = ({ number, add }) => {  return (    

count组件

count: {number}

);};export default connect((state) => ({ number: state.number })) (Index);

三、 Redux 数据交互

1. 异步操作处理

安装 Redux Thunk:

yarn add redux-thunk

创建 store:

import { createStore, applyMiddleware } from 'redux';import reducer from '../reducers/reducers';import thunk from 'redux-thunk';const store = createStore(reducer, applyMiddleware(thunk));export default store;

actionCreators.js 中添加异步逻辑:

export const actionCreators = {  add: () => ({    type: 'ADD',  }),  getInfo: () => dispatch => {    fetch('/data.json')      .then(res => res.json())      .then(data => {        dispatch({          type: 'GET_INFO',          payload: data,        });      });  },};

四、 Redux 与 DVA 对比

Redux 是一款基于 Immer.js 的状态管理库,适合处理复杂的异步状态逻辑。而 DVA 则是一种轻量级的状态管理方案,适合简单的状态管理需求。两者可以根据项目需求灵活选择。

转载地址:http://sqcg.baihongyu.com/

你可能感兴趣的文章
NumPy 库详细介绍-ChatGPT4o作答
查看>>
NumPy 或 Pandas:将数组类型保持为整数,同时具有 NaN 值
查看>>
numpy 或 scipy 有哪些可能的计算可以返回 NaN?
查看>>
numpy 数组 dtype 在 Windows 10 64 位机器中默认为 int32
查看>>
numpy 数组与矩阵的乘法理解
查看>>
NumPy 数组拼接方法-ChatGPT4o作答
查看>>
numpy 用法
查看>>
Numpy 科学计算库详解
查看>>
Numpy.fft.fft和numpy.fft.fftfreq有什么不同
查看>>
numpy.linalg.norm(求范数)
查看>>
Numpy.ndarray对象不可调用
查看>>
Numpy.VisibleDeproationWarning:从不整齐的嵌套序列创建ndarray
查看>>
Numpy:按多个条件过滤行?
查看>>
Numpy:条件总和
查看>>
numpy、cv2等操作图片基本操作
查看>>
numpy中的argsort的用法
查看>>
NumPy中的精度:比较数字时的问题
查看>>
numpy判断对应位置是否相等,all、any的使用
查看>>
Numpy多项式.Polynomial.fit()给出的系数与多项式.Polyfit()不同
查看>>
Numpy如何使用np.umprod重写range函数中i的python
查看>>