建设银行网站号,公司网站设计广州,视频制作和剪辑教程,昆明网络营销网站1.redux的介绍
Redux – 李立超 | lilichao.com
2.react-redux
1#xff09;react-Redux将所有组件分成两大类
UI组件 只负责 UI 的呈现#xff0c;不带有任何业务逻辑通过props接收数据(一般数据和函数)不使用任何 Redux 的 API一般保存在components文件夹下容器组件 …1.redux的介绍
Redux – 李立超 | lilichao.com
2.react-redux
1react-Redux将所有组件分成两大类
UI组件 只负责 UI 的呈现不带有任何业务逻辑通过props接收数据(一般数据和函数)不使用任何 Redux 的 API一般保存在components文件夹下容器组件 负责管理数据和业务逻辑不负责UI的呈现使用 Redux 的 API一般保存在containers文件夹
2react-redux相比较于react的不同在于它提供了一些api来方便我们使用redux 1.Provider 组件 Provider是react-redux库提供的顶层组件它可以包裹整个React应用。通过ProviderRedux的store可以被传递给整个React组件树使得所有的组件都能够访问Redux的状态。 2.connect 函数 connect是react-redux提供的函数它可以连接React组件与Redux的store并在组件中注入Redux的状态和操作。这样组件就能够通过props直接访问Redux中的状态而不需要手动订阅状态变化或分发actions。
代码示例还是以一个简单的计数器作为例子 创建Redux store 和 reducer
// 文件store.js
import { createStore } from redux;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;}
};const store createStore(counterReducer);export default store;创建React组件使用react-redux中的connect函数连接React组件与Redux store
// 文件Counter.js
import React from react;
import { connect } from react-redux;const Counter ({ count, increment, decrement }) (divpCount: {count}/pbutton onClick{increment}Increment/buttonbutton onClick{decrement}Decrement/button/div
);const mapStateToProps (state) ({count: state.count,
});const mapDispatchToProps (dispatch) ({increment: () dispatch({ type: INCREMENT }),decrement: () dispatch({ type: DECREMENT }),
});export default connect(mapStateToProps, mapDispatchToProps)(Counter);在应用的入口文件中使用Provider组件将Redux store传递给整个应用
// 文件index.js
import React from react;
import ReactDOM from react-dom;
import { Provider } from react-redux;
import store from ./store;
import Counter from ./Counter;const App () (Provider store{store}Counter //Provider
);ReactDOM.render(App /, document.getElementById(root));3.dva.js
1dvajs全称是DvaJS是一个基于React和Redux的前端应用框架。它是一个由阿里巴巴出品的框架旨在简化React应用的开发流程尤其是在状态管理方面。DvaJS借鉴了Redux的思想但在其基础上进行了封装提供了一些方便开发的额外特性。
官网快速上手 | DvaJS
与传统的Redux和React-Redux相比DvaJS 提供了更加简化和约定的开发方式主要包括以下几个核心概念 Model DvaJS引入了Model的概念将数据、业务逻辑和界面表现进行了组织。一个Model包括state、reducers、effects等内容使得相关的代码可以更容易地维护在一起。 Effects Effects是用于处理异步操作例如数据请求的地方。在DvaJS中Effects通过Redux-saga来处理异步流程使得异步逻辑更加清晰。 Reducer和Action的简化 DvaJS封装了Redux的Reducer和Action的创建通过一些简单的约定减少了编写冗长的Reducer和Action的代码。 Router的集成 DvaJS内置了React-Router使得路由的管理变得更加简单。
计数器实例
// models/counter.js
export default {namespace: counter,state: 0,reducers: {increment(state) {return state 1;},decrement(state) {return state - 1;},},
};// index.js
import React from react;
import dva from dva;
import { connect } from dva;
import Counter from ./Counter;// 创建dva应用
const app dva();// 注册Model
app.model(require(./models/counter).default);// 注册路由
app.router(() Counter /);// 启动应用
app.start(#root);4.RTK
Redux ToolkitRTK – 李立超 | lilichao.com