IT이야기

Vuex 작업 유형을 알 수 없는 이유는 무엇입니까?

cyworld 2022. 6. 7. 21:33
반응형

Vuex 작업 유형을 알 수 없는 이유는 무엇입니까?

작업 유형을 알 수 없는 이유와 수정 사항은 무엇입니까?

이게 흔한 문제라는 걸 알아요.SO를 검색해보니 20개까지의 답변이 있으며, 그 중 많은 답변이 mapActions와 관련되어 있습니다.대부분의 답변을 읽고 mapActions 구문을 무수히 변형시켜 봤지만 아직도 제 코드에 문제가 있는지 알 수 없습니다.

알겠습니다. 컴포넌트(또는 모듈)에서 디스패치를 호출하면 Vuex 스토어(실제 값이 변경되는 곳)에서 변환됩니다.

또, 지적하는 것이 도움이 될지 어떨지 모르겠지만, 아래의 상태 사진에서는 동작이나 돌연변이를 볼 수 있을 것이라고 기대했지만, 할 수 없습니다.

업데이트:

다른 몇 가지 제안과 같이 코드를 편집한 후에도 결과는 동일합니다.알 수 없는 액션 유형: toggleIsCategory휠 스핀, {}

관련이 있는지는 모르겠지만 디스패치가 호출되는 회선myStore.dispatch("toggleIsCategoryWheelSpinning,{}");Wheel.vue는 중첩된 함수 안에 있습니다.


여기에 이미지 설명 입력

코드는 다음과 같습니다.

 //Wheel.vue

    <template>
    <div >
        <div id="chart"></div>
    </div>
</template>

<script type="text/javascript" charset="utf-8">
import store from 'vuex'
import { mapActions} from 'vuex'

export default {
    name: "wheel",
    props: {
        wheelCategories: {
            type: Array,
            required: true,
        },
        expressions: {
            type: Array,
            required: true,
        },
    },
    data() {
        return {
        };
    },
    mounted() {
        let myscript = document.createElement("script");
        myscript.setAttribute("src", "https://d3js.org/d3.v3.min.js");
        document.head.appendChild(myscript);
        myscript.onload = this.createWheel(this.wheelCategories,this.expressions, this.$store);
    },
    methods: {
        ...mapActions(['toggleIsCategoryWheelSpinning']),   
        created(){
            this.toggleIsCategoryWheelSpinning       
        },

        createWheel: function (wheelCategories,expressions, myStore) {
            var padding = { top: 20, right: 40, bottom: 20, left: 20 },
                w = 500 - padding.left - padding.right,
                h = 500 - padding.top - padding.bottom,
                r = Math.min(w, h) / 2,
                rotation = 0,
                oldrotation = 0,
                picked = 100000,
                oldpick = [],
                color = d3.scale.category20();
            
            var svg = d3
                .select("#chart")
                .append("svg")
                .data([wheelCategories])
                .attr("width", w + padding.left + padding.right)
                .attr("height", h + padding.top + padding.bottom);
            
            var container = svg
                .append("g")
                .attr("class", "chartholder")
                .attr(
                    "transform",
                    "translate(" +
                        (w / 2 + padding.left) +
                        "," +
                        (h / 2 + padding.top) +
                        ")"
                )
                .style({ cursor: "grab" });

            var vis = container.append("g");

            var pie = d3.layout
                .pie()
                .sort(null)
                .value(function (d) {
                    return 1;
                });

            var arc = d3.svg.arc().outerRadius(r);

            var arcs = vis
                .selectAll("g.slice")
                .data(pie)
                .enter()
                .append("g")
                .attr("class", "slice");
            
            arcs.append("path")
                .attr("fill", function (d, i) {
                    return color(i);
                })
                .attr("d", function (d) {
                    return arc(d);
                });

            // add the text
            arcs.append("text").attr("transform", function (d) {
                d.innerRadius = 0;
                d.outerRadius = r;
                d.angle = (d.startAngle + d.endAngle) / 2;
                return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")translate(" + (d.outerRadius -10) +")";
            })
            .attr("text-anchor", "end")
                .text(function (d, i) {
                    return wheelCategories[i].label;                 
                });

            container.on("click", spin);  

            function spin(d) {
                container.on("click", null);
                //the following line gives the "unknown action"
                myStore.dispatch("toggleIsCategoryWheelSpinning,{}");
                console.log('dispatch finished');

                //all slices have been seen, all done
                if (oldpick.length == wheelCategories.length) {
                    document.getElementById("spinResponse"
                    ).innerHTML = `out of spins`;
                    container.on("click", null);
                    return;
                }

                var ps = 360 / wheelCategories.length,
                    pieslice = Math.round(1440 / wheelCategories.length),
                    rng = Math.floor(Math.random() * 1440 + 360);

                rotation = Math.round(rng / ps) * ps;

                picked = Math.round(
                    wheelCategories.length - (rotation % 360) / ps
                );
                picked =
                    picked >= wheelCategories.length
                        ? picked % wheelCategories.length
                        : picked;

                if (oldpick.indexOf(picked) !== -1) {
                    d3.select(this).call(spin);
                    return;
                } else {
                    oldpick.push(picked);
                }

                rotation += 90 - Math.round(ps / 2);

                let index = Math.floor(Math.random() * expressions.length); // 10  returns a random integer from 0 to 9

                vis.transition()
                    .duration(3000)
                    .attrTween("transform", rotTween)
                    .each("end", function () {
                        oldrotation = rotation;
                        container.on("click", spin);
                    });
            }

            //make arrow
            svg.append("g")
                .attr(
                    "transform",
                    "translate(" +
                        (w + padding.left + padding.right) +
                        "," +
                        (h / 2 + padding.top) +
                        ")"
                )
                .append("path")
                .attr(
                    "d",
                    "M-" +
                        r * 0.15 +
                        ",0L0," +
                        r * 0.05 +
                        "L0,-" +
                        r * 0.05 +
                        "Z"
                )
                .style({ fill: "black" });

            //draw spin circle
            container
                .append("circle")
                .attr("cx", 0)
                .attr("cy", 0)
                .attr("r", 60)
                .style({ fill: "white", cursor: "grab" });

            //spin text
            container
                .append("text")
                .attr("x", 0)
                .attr("y", 15)
                .attr("text-anchor", "middle")
                .text("SPIN ME!")
                .style({
                    "font-weight": "bold",
                    "font-size": "25px",
                    cursor: "grab",
                });

            function rotTween(to) {
                var i = d3.interpolate(oldrotation % 360, rotation);
                return function (t) {
                    return "rotate(" + i(t) + ")";
                };
            }

            function getRandomNumbers() {
                var array = new Uint16Array(1000);
                var scale = d3.scale
                    .linear()
                    .range([360, 1440])
                    .domain([0, 100000]);

                if (
                    window.hasOwnProperty("crypto") &&
                    typeof window.crypto.getRandomValues === "function"
                ) {
                    window.crypto.getRandomValues(array);
                    console.log("works");
                } else {
                    //no support for crypto, get crappy random numbers
                    for (var i = 0; i < 1000; i++) {
                        array[i] = Math.floor(Math.random() * 100000) + 1;
                    }
                }

                return array;
            }
        }
    }
    
};

//end code for wheel
</script>

<style type="text/css" scoped>
text {
    font-size: 15px;
    pointer-events: grab;
}
#chart {
    /* cursor: grab; */
    margin: 0 auto;
    border: 10px;
}
#question {
    text-align: center;
}
#question h1 {
    font-size: 50px;
    font-weight: bold;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    /* position: absolute; */
    padding: 0;
    margin: 0;
    top: 50%;
    -webkit-transform: translate(0, -50%);
    transform: translate(0, -50%);
}

#spinResponse {
    font-size: 30px;
    text-align: center;
    width: 500px;
    padding-bottom: 30px;
    background-color: rgb(129, 19, 19);
    font-weight: bold;
}

</style>

부엑스 스토어

// store/index.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const foodCategories = [
   //...
];

const expressions = [
   //...
];

const isCategoryWheelSpinning = false;

export default new Vuex.Store({
  state: {
    foodCategories,
    expressions,
    isCategoryWheelSpinning,
  },
  getters: {
  },    
  actions: {
    toggleIsCategoryWheelSpinning(context,payload){
        context.commit("toggleIsCategoryWheelSpinning",payload);
    }
  },
  mutations: {
   toggleIsCategoryWheelSpinning(state, payload) {
      state.isCategoryWheelSpinning = !isCategoryWheelSpinning;
    },
  },
});

그리고 메인이요.

// src/main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store';

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

작업 이름이 일치하지 않습니다.코드와 같아야 합니다.다음을 사용해 보십시오....mapActions(["toggleIsCategoryWheelSpinning"]동작을 Import하기 위해

고객님의 고객명actions가게에서는, 라고 하는 행동은 없습니다.action_toggleIsCategoryWheelSpinning하지만, 라고 불리는 것이 있습니다.toggleIsCategoryWheelSpinningmapActions에서는 다음 항목을 Import해야 합니다.

methods: {
  mapActions(['toggleIsCategoryWheelSpinning'])
}

@Tao(아래 참조)의 코멘트는 (해답)으로 이어집니다.구체적으로는 굵은 글씨 텍스트입니다.

다음 코드 편집으로 문제가 해결되었습니다.

Wheel.vue에서 메서드 섹션을 편집합니다.

...mapActions(['toggleIsCategoryWheelSpinning']),   
created(){
    this.toggleIsCategoryWheelSpinning       
},

디스패치가 호출되면 첫 번째 행에서 두 번째 행으로 변경됩니다.

myStore.dispatch("toggleIsCategoryWheelSpinning,{}");    
myStore.dispatch("toggleIsCategoryWheelSpinning",{});

액션은 {module/}{action}(모듈 사용 시 모듈 이름 포함) 형식의 문자열인 name과 payload의 두 가지 매개 변수를 사용하여 호출됩니다. payload는 개체(또는 어레이, 여전히 개체) 또는 원시(문자열, 부울, 숫자 등)일 수 있습니다.디스패치라고 불러주세요("toggle Is Category")빈 개체를 payload로 사용하여 호출하는 경우 WheelSpinning", {}.name 파라미터 내에 payload를 배치하면 기존의 액션에 매핑되지 않는 문자열이 됩니다.– tao 30분 전

언급URL : https://stackoverflow.com/questions/65471546/why-is-the-vuex-action-type-unknown

반응형