【问题标题】:React (Typescript) using Hooks to add/remove cubes; addCube works but removeCube doesn'tReact (Typescript) 使用 Hooks 添加/删除多维数据集; addCube 有效,但 removeCube 无效
【发布时间】:2022-11-16 06:46:44
【问题描述】:

来自我的 Hooks“useStore.tsx”的完整代码,是根据教程构建的。除了“removeCube”之外,这里的一切都完美无缺。没有错误,它只是没有删除多维数据集。任何提示将不胜感激!

完整代码在这里:https://github.com/He-fast-us/Tunnel-Art

`

import create from 'zustand';
import { nanoid } from 'nanoid';
import { Triplet } from '@react-three/cannon';
import * as textures from '../Images/textures';
import { useState } from 'react';

const getLocalStorage = (key: string) => JSON.parse(window.localStorage.getItem(key)!)
const setLocalStorage = (key: string, value: unknown) => (window.localStorage.setItem(key, JSON.stringify(value)))

type TextureId = keyof typeof textures

type State = {
    texture: TextureId,
    cubes: Array<{ key: string, pos: Triplet, texture: TextureId }>,
    addCube: (x: number, y: number, z: number) => void,
    removeCube: (x: number, y: number, z: number) => void,
    saveWorld: () => void,
    resetWorld: () => void,
    setTexture: (texture: TextureId) => void,
}

export const useStore = create<State>((set) => ({
    texture: 'dirtTexture',
    cubes: getLocalStorage('cubes') || [],
    addCube: (x, y, z) => {
        set((prev) => ({
            cubes: [
                ...prev.cubes,
                {
                    key: nanoid(),
                    pos: [x, y, z],
                    texture: prev.texture
                }
            ]
        }))
    },

    removeCube: (x, y, z) => {
        set((prev) => ({
            cubes: prev.cubes.filter(cube => {
                const [X, Y, Z] = cube.pos
                return X !== x || Y !== y || Z !== z
            })
        }))
    },

    setTexture: (texture) => {
        set(() => ({
            texture
        }))
    },

    saveWorld: () => {
        set((prev) => {
            setLocalStorage('cubes', prev.cubes)
        })
    },
    resetWorld: () => {
        set(() => ({
            cubes: []
        }))
    },
}))

`

我检查了拼写错误并确认添加和删除匹配的语法,但我正在努力查看这里有什么不起作用

【问题讨论】:

    标签: reactjs typescript redux react-hooks state


    【解决方案1】:

    找到我的答案!

    事实证明 removeCube 的编码是正确的,但只有在用户按住 alt 键时才有效。这是在一个单独的文件 Cube.tsx 中,我不得不更改它:

    if(e.button == 2){
                removeCube(x, y, z)
                return
            }
    

    以前是:

        if(e.altKey){
                removeCube(x, y, z)
                return
            }
    

    改变电子。部分将其设置为按住 Alt 以删除立方体,右键单击 ( ... == 0) 左键单击,( ... == 1) 中心单击)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 2021-03-01
      • 2020-08-02
      • 1970-01-01
      • 2022-01-05
      • 2020-07-24
      • 2020-06-03
      相关资源
      最近更新 更多