gpt4 book ai didi

javascript - 使用 Lodash.remove 通过 Vuex 突变更改状态不会触发我的 Vue 组件中的响应式(Reactive)重新渲染

转载 作者:行者123 更新时间:2023-12-01 15:38:13 28 4
gpt4 key购买 nike

我有一个接收 Villager 数组的组件进入它的prop从父组件。父组件从 this.$store.state 中提取该数组。 .

return this.$store.state.villages.find(value => value.id === 0).villagers
我执行 this.$store.mutation提交之后更改给定的数组。正如您在下面的屏幕截图中看到的那样,突变确实有效。但是,我所在的组件没有重新渲染,并且仍然显示 3 而不是 2 项。
react 链似乎在某处被打破,但我无法确定恶魔。我以为 props值(value)是一种 react 机制。正如您在屏幕截图中看到的,它的值已更改,但 DOM 并未相应更新。
enter image description here
代码摘录
我试图提取问题的相关部分
存储/索引.ts
[...]
export default new Vuex.Store({
state: {
villages: [
{
id: 0,
name: 'Peniuli',
foundingDate: 20,
villagers: [
{
id: '33b07765-0ec6-4600-aeb1-43187c362c5a1',
name: 'Baltasar',
bloodline: 'Gent',
occupation: 'Farmer'
},
[...]
mutations: {
disbandVillager (state, payload) {
const villagerId = payload.id
const village = state.villages.find(value => value.id === 0)
console.debug('disbanding villager:', villagerId)
if (!_.isNil(village)) {
console.debug('bfore:', village.villagers)
_.remove(village.villagers, function (n) {
return n.id === villagerId
})
console.debug('after:', village.villagers)
}
}
},
[...]

村庄.vue
<template>
<Villagers :villagers="playerVillage.villagers"></Villagers>
</template>
[...]
computed: {
playerVillage: function () {
return this.$store.state.villages.find(value => value.id === 0)
}
}
[...]
村民.vue
<template>
<v-container>
<v-card v-for="villager in villagers" :key="villager.id">
<v-row>
<v-col>
<v-card-title>Name: {{villager.name}}</v-card-title>
</v-col>
<v-col>
<v-card-title>Bloodline: {{villager.bloodline}}</v-card-title>
</v-col>
<v-col>
<v-card-title>Occupation: {{villager.occupation}}</v-card-title>
</v-col>
<v-col v-if="managable">
<DisbandButton :villager="villager"></DisbandButton>
</v-col>
</v-row>
</v-card>
</v-container>
</template>

<script>
import DisbandButton from '@/components/village/DisbandButton'

export default {
name: 'Villagers',
components: { DisbandButton },
props: [
'villagers',
'managable'
]
}
</script>
DisbandButton.vue
<template>
<v-btn @click="disbandVillager" color="red">Disband</v-btn>
</template>

<script>
export default {
name: 'DisbandButton',
props: ['villager'],
methods: {
disbandVillager: function () {
this.$store.commit('disbandVillager', { id: this.villager.id })
}
}
}
</script>

最佳答案

假设那是 lodash 那么我相信问题是你正在使用 _.remove .
内部 _.remove以不会触发 Vue 的 react 系统的方式实现。具体在这里:
https://github.com/lodash/lodash/blob/ded9bc66583ed0b4e3b7dc906206d40757b4a90a/lodash.js#L3859
那是使用默认数组 splice方法,而不是 Vue 提供的自定义覆盖。
像这样的东西应该工作:

village.villagers = village.villagers.filter(function (n) {
return n.id !== villagerId
})

关于javascript - 使用 Lodash.remove 通过 Vuex 突变更改状态不会触发我的 Vue 组件中的响应式(Reactive)重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445948/

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