博客
关于我
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/

你可能感兴趣的文章
Nodejs express 获取url参数,post参数的三种方式
查看>>
nodejs http小爬虫
查看>>
nodejs libararies
查看>>
nodejs npm常用命令
查看>>
Nodejs process.nextTick() 使用详解
查看>>
NodeJS 导入导出模块的方法( 代码演示 )
查看>>
nodejs 的 Buffer 详解
查看>>
nodejs 读取xlsx文件内容
查看>>
nodejs 运行CMD命令
查看>>
nodejs+nginx获取真实ip
查看>>
nodejs-mime类型
查看>>
NodeJs——(11)控制权转移next
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
nodejs与javascript中的aes加密
查看>>
nodejs中Express 路由统一设置缓存的小技巧
查看>>
Nodejs中的fs模块的使用
查看>>
nodejs包管理工具对比:npm、Yarn、cnpm、npx
查看>>
NodeJs单元测试之 API性能测试
查看>>
nodejs图片转换字节保存
查看>>