代码之家  ›  专栏  ›  技术社区  ›  Cdhippen

我的元素不会在我的鼓应用程序中更新动作分派后的显示

  •  0
  • Cdhippen  · 技术社区  · 6 年前

    我正在构建一个react/redux drum应用程序,我需要使用的最后一个组件是一个元素,该元素通过动作分派用所选对象的id进行更新。我不明白为什么它不会更新元素,即使我可以确认当我将id作为属性传入时,操作会记录它。

    我的代码沙盒链接在这里: https://codesandbox.io/s/k29r3928z7

    元素是 <div id="display">{display}</div>

    行动是

    export const drumHit = (url, id) => {
      const sound = new Audio(url);
      sound.play();
      console.log(id);
    
      return {
        type: "HIT",
        id
      };
    };
    

    减速机在这里:

    const switchReducer = (state = { value: "Hello", display: "" }, action) => {
      switch (action.type) {
        case "SWITCH":
          return { ...state, value: action.value };
    
        case "HIT":
          return { ...state, display: action.id };
    
        default:
          return state;
      }
    };
    

    如果你能帮我把这个弄起来,我将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Anthony    6 年前

    从沙盒:

    const mapDispatchToProps = dispatch => ({
      switcheroo: val => dispatch(switcheroo(val)),
      drumHit: id => dispatch(drumHit(id))
    });
    

    你不给 url 你的参数 drumHit() 你的行动 mapDispatchToProps ,所以 id 定义中的第二个参数 undefined .

    另外,你的 handleKeyPress 方法

    handleKeyPress = event => {
        const drumKey = drumObj.find(obj => obj.keyCode === event.keyCode);
    
        if (drumKey) {
          drumHit(drumKey.url, drumKey.id);
        }
      };
    

    正在使用导入的 drumHit 直接与来自 this.props 这意味着这个动作实际上不会被分配给你的减速器这就是为什么 console 显示预期的 身份证件 当你按着键玩的时候, 网址 身份证件 都通过了。

    编辑:

    你的 mapStateToProps 正在使用 state.id ,但减速器正在设置 身份证件 display ,所以您只需将其更改为:

    const mapStateToProps = state => ({
      value: state.value,
      url: state.url,
      display: state.display
    });