gpt4 book ai didi

javascript - mapGetters 仅在第一次加载时出现 react 性问题

转载 作者:搜寻专家 更新时间:2023-10-30 22:17:11 24 4
gpt4 key购买 nike

我正在使用来自 VueX 的 mapGetters 帮助程序,但我只在页面的第一次加载时遇到一些问题,它不是 react 性的......让我告诉你:

我的 html 模板触发了更改:

<input type="number" value="this.inputValue" @change="this.$store.dispatch('setInputValue', $event.target.value)">

我的商店收到值(value)

{
state: {
appValues: {
inputValue: null
},
},
getters: {
getInputValue: (state) => {
return state.appValues.inputValue;
},
},
mutations: {
setInputValue(state, value) {
state.appValues.inputValue = value;
},
},
actions: {
setInputValue(context, payload) {
return new Promise((resolve, reject) => {
context.commit('setInputValue', payload);
resolve();
});
},
}
}

然后我的组件监听商店:

import {mapGetters} from 'vuex';

computed: {
...mapGetters({
inputValue: 'getInputValue',
}),
}
watch: {
inputValue: {
deep: true,
immediate: true,
handler(nVal, oVal) {
console.log("inputValue", nVal, oVal);
}
},
}

所以现在,当我第一次加载页面时,我得到这个 console.log "inputValue"null undefined 这是完全正常的,因为我的商店里什么都没有,它给了我默认值

但现在是奇怪的部分。我开始更改输入值,但我的控制台中没有显示任何内容。什么都没有动...

然后我重新加载页面,在加载时我得到这个 console.log "inputValue"5 undefined(5 是我之前输入的值)所以你可以看到,当我改变之前输入,它很好地将值保存在商店中,但计算值不会自行更新...

现在回答,当我更改输入的值时,我的控制台日志是这样的 "inputValue"7 5 所以它的工作方式就像我希望的那样从一开始就工作...

我做错了什么?为什么在第一次加载时计算值不是 react 性的?

感谢您的回答...

最佳答案

我认为解决这个问题最好的方法是用watcher存储一个局部变量,然后在局部发生变化时更新vuex:

在你的组件上:

<input type="number" v-model="value">

data() {
return {
value: ''
};
},

computed: {
...mapGetters({
inputValue: 'getInputValue'
})
}

watch: {
value(value){
this.$store.dispatch('setInputValue', value);
},

inputValue(value) {
console.log('inputValue', value);
}
},

created() {
// set the initial value to be the same as the one in vuex
this.value = this.inputValue;
}

关于javascript - mapGetters 仅在第一次加载时出现 react 性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56986389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com