更新状态时组件不重新呈现

时间:2017-12-22 19:12:22

标签: vue.js vuex

我一直在尝试调试这个,但由于某种原因,当我从创建的生命周期函数中的外部API中提取数据并使用变异更新存储时,组件的计算属性即将获得状态更新导致组件不重新渲染。有什么想法吗?

以下是组件的模板:

<template>
    <div class="list">
        <ul>
            <ListItem v-for="transaction in transactions" :list-item-data="transaction" :key="transaction.txid"/>
        </ul>
    </div>
</template>

<script>
    import ListItem from './ListItem.vue';
    import External from '../ExternalAPI';

    export default {
        methods: {
            fetchData() {
                return ExternalAPI.fetch(data => {
                    this.$store.dispatch('setTransactions', data);
                });
            }
        },
        components: {
            ListItem
        },
        computed: {
            transactions () {
                return this.$store.getters.transactions;
            },
        },
        created() {
            this.fetchData();
        },
    }
</script>

这是商店:

export const store = new Vuex.Store({
    state: {
      transactions: [],
    },
    getters: {
      transactions: state => {
        return state.transactions;
      }
    },
    mutations: {
      setTransactions: (state, transactions) => {
        let txs = transactions.map(transaction => {
            return new Transaction(transaction.id, transaction.prop1, transaction.prop2);
        });
        state.transactions = txs;
      },
    },
    actions: {
      setTransactions: (context, transactions) => {
        context.commit('setTransactions', transactions);
      },
    },
});

1 个答案:

答案 0 :(得分:1)

vuex状态树中的任何内容都需要是原始的普通对象或数组。我无法在文档中找到任何明确说明的内容,但我找到了comment on vuex issue 153

您在Transaction突变中实例化了一些setTransactions。尝试将其更改为

setTransactions: (state, transactions) => {
  let txs = transactions.map(transaction => {
    return {
      id: transaction.id,
      prop1: transaction.prop1,
      prop2: transaction.prop2
    };
  });
  state.transactions = txs;
},