计算属性未响应界面变化
itmanyong opened this issue · comments
itmanyong commented
幻魂 commented
你好这个计算函数看起来并没有问题,你有打断点试试,能够进去吗,或者提供一个能够复现问题的codesandbox链接我看下
itmanyong commented
https://codesandbox.io/s/crazy-yalow-4cpkc console可见state和computed
幻魂 commented
幻魂 commented
你仔细检查你的逻辑哈
幻魂 commented
幻魂 commented
推荐build是打一份es
源码,这样方便codesandbox
调试,然后就是我找到原因了,问题出在这里
https://github.com/itmanyong/cxy-react-i18n/blob/master/src/i18n/watch.js
watch调用reducer方法时,流程中的数据其实还没有落到store
changeState(by reducer, setState) ---> trigger computed ---> trigger watch ---> save changedState to store
所以此时reducer里的调用再次触发的计算函数是拿不到最新的state的,你需要延迟一下
即将代码
import { MODEL_NAME, STORE_LANG_KEY } from '../configs/vars';
/**
* 根据当前lang的存在性重置lang
*/
export const watch_lang_message = {
fn: ({ lang, message }, o, f) => {
if (!lang && Object.keys(message)[0]) {
if (localStorage.getItem(STORE_LANG_KEY)) {
f.refCtx.reducer[MODEL_NAME].setLang(localStorage.getItem(STORE_LANG_KEY));
} else {
f.refCtx.reducer[MODEL_NAME].setLang(Object.keys(message)[0]);
}
}
if (lang && lang != o.lang) {
localStorage.setItem(STORE_LANG_KEY, lang);
}
},
depKeys: ['lang', 'message'],
compare: true,
immediate: true,
};
改为
import { MODEL_NAME, STORE_LANG_KEY } from '../configs/vars';
import { dispatch, reducer } from 'concent';
// 延迟到下一个事件循环执行reducer函数,确保watch流程中的改变数据先落地,之后触发的另外一轮computed函数
// 拿到的计算函数是正确的啦
const invokeReducer = (reducer, payload) => setTimeout(() => dispatch(reducer, payload), 0);
/**
* 根据当前lang的存在性重置lang
*/
export const watch_lang_message = {
fn: ({ lang, message }, o) => {
if (!lang && Object.keys(message)[0]) {
const setLang = reducer[MODEL_NAME].setLang;
if (localStorage.getItem(STORE_LANG_KEY)) {
invokeReducer(setLang, localStorage.getItem(STORE_LANG_KEY));
} else {
invokeReducer(setLang, Object.keys(message)[0]);
}
}
if (lang && lang != o.lang) {
localStorage.setItem(STORE_LANG_KEY, lang);
}
},
depKeys: ['lang', 'message'],
compare: true,
immediate: true,
};
我准备下一版本把在f
上绑一个函数 nextTickDispatch
,方便用户安全的调用reducer方法
itmanyong commented
阿西吧!之前也怀疑过这个watch,因为独立出来store之后是正常的。。。请教下:build的es源码模式怎么配置呢
幻魂 commented
copy 一份 src 的源码 放 es目录即可
itmanyong commented
感谢!!!