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

本文共 2289 字,大约阅读时间需要 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/

你可能感兴趣的文章
Node.js官网无法正常访问时安装NodeJS的方法
查看>>
node.js模块、包
查看>>
node.js的express框架用法(一)
查看>>
Node.js的交互式解释器(REPL)
查看>>
Node.js的循环与异步问题
查看>>
Node.js高级编程:用Javascript构建可伸缩应用(1)1.1 介绍和安装-安装Node
查看>>
nodejs + socket.io 同时使用http 和 https
查看>>
NodeJS @kubernetes/client-node连接到kubernetes集群的方法
查看>>
NodeJS API简介
查看>>
Nodejs express 获取url参数,post参数的三种方式
查看>>
nodejs http小爬虫
查看>>
nodejs libararies
查看>>
nodejs npm常用命令
查看>>
nodejs npm常用命令
查看>>
Nodejs process.nextTick() 使用详解
查看>>
NodeJS yarn 或 npm如何切换淘宝或国外镜像源
查看>>
nodejs 中间件理解
查看>>
nodejs 创建HTTP服务器详解
查看>>
nodejs 发起 GET 请求示例和 POST 请求示例
查看>>
NodeJS 导入导出模块的方法( 代码演示 )
查看>>