Redux 是 JavaScript 状态容器,提供可预测化的状态管理。Redux 除了和 React 一起用外,还支持其它界面库。它体小精悍(只有2kB,包括依赖)。
https://github.com/xuya227939/blog/tree/master/examples/react-redux/my-app
$ sudo npm install -g create-react-app
$ create-react-app my-app
$ cd my-app
$ npm install --save redux
1.修改App.js,引用官方代码。
import React from 'react'; import { createStore } from 'redux'; function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: return state } } let store = createStore(counter) store.subscribe(() => console.log(store.getState()) ) store.dispatch({ type: 'INCREMENT' }) store.dispatch({ type: 'INCREMENT' }) store.dispatch({ type: 'DECREMENT' }) const BasicExample = () => ( 123) export default BasicExample
2.npm start 调出开发者工具,看console.log输出。
这里以计数器为例子
https://github.com/xuya227939/blog/tree/master/examples/saga/my-app
$ sudo npm install -g create-react-app
$ create-react-app my-app
$ cd my-app
$ npm install --save redux
$ npm install --save redux-saga
export function* addFun() { yield put({ type: "ADD" }); } function* homeSaga() { yield takeEvery("ADD_SAGA", addFun); }
function*
Generato函数
监听action
逻辑处理homeSaga函数addFun函数
yield put({ type: "ADD" });
类似action的dispatch,发送数据到reducer
1.如果报类似这样的错,react-scripts command not found 那么就 $ rm -rf node_modules 模块,重新安装下 $ npm i,再重新npm start
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者