比如:在小程序里面,我不想要redux或者vuex,那么如何进行状态、数据管理?
说人话:就是如何实现简单的redux或者vuex?
比如:在小程序里面,我不想要redux或者vuex,那么如何进行状态、数据管理?
说人话:就是如何实现简单的redux或者vuex?
用户的使用方式非常简单
用户之间没有协作
不需要与服务器大量交互,也没有使用 WebSocket
视图层(View)只从单一来源获取数据
以上几种情况是不需要用到redux的
某个组件的状态,需要共享
某个状态需要在任何地方都可以拿到
一个组件需要改变全局状态
一个组件需要改变另一个组件的状态
这种情况下是需要flux或者redux来管理状态的
你也可以模仿redux的实现方式,创建一个store来统一管理数据的更新,共享,参考redux的api,用store.getState()来获取状态或数据,用action来发送通知等等。
function reducer(state, action) {
/* 初始化 state 和 switch case */
if (!state) {
return {
title: {
text: 'React.js',
color: 'red'
},
content: {
text: 'React.js and Redux',
color: 'blue'
}
}
}
switch (action.type) {
case 'UPDATE_TITLE_TEXT':
return {
...state,
title: {
...state.title,
text: action.text
}
};
case 'UPDATE_TITLE_COLOR':
return {
...state,
title: {
...state.title,
color: action.color
}
};
default:
return state;
}
}
// 生成 store
function createStore(reducer) {
let state = null;
const listeners = [];
const subscribe = (listener) => listeners.push(listener);
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach((listener) => {
listener();
});
};
dispatch({}); // 初始化 state
return {
getState,
dispatch,
subscribe
}
}
// 生成 store
const store = createStore(reducer);
let oldState = store.getState(); // 缓存旧的state
// 监听数据变化重新渲染页面
store.subscribe(() => {
const newState = store.getState();
renderApp(newState, oldState);
oldState = newState;
});
function renderTitle(newTitle, oldTitle) {
if (newTitle === oldTitle) {
return;
}
console.log('render title...')
const titleDOM = document.getElementById('title');
titleDOM.innerHTML = newTitle.text;
titleDOM.style.color = newTitle.color;
}
function renderContent(newContent, oldContent) {
if (newContent === oldContent) {
return;
}
console.log('render content...')
const contentDOM = document.getElementById('content');
contentDOM.innerHTML = newContent.text;
contentDOM.style.color = newContent.color;
}
function renderApp(newAppState, oldAppState = {}) {
if (newAppState === oldAppState) {
return;
}
console.log('render app...')
renderTitle(newAppState.title, oldAppState.title);
renderContent(newAppState.content, oldAppState.content);
}
// 首次渲染页面
renderApp(store.getState());
// 后面可以随意 dispatch 了,页面自动更新
store.dispatch({type: 'UPDATE_TITLE_TEXT', text: 'React.js is good'}); // 修改标题文本
store.dispatch({type: 'UPDATE_TITLE_COLOR', color: 'blue'}); // 修改标题颜色
基本的redux功能实现了
13 回答13k 阅读
7 回答2.2k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.3k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
自己写个class,定义初始的初始数据(__state),
修改数据时用原型上的函数进行:
获取数据时通过ES6 的get来获取,具体实现:
其实还是能直接修改到数据,但是经过包装后,隐藏掉这个接口,而且实现也比较简单。