Javascript 我的元素赢了';t在我的鼓应用程序中更新动作分派后的显示
我正在构建一个React/Redux drum应用程序,我需要使用的最后一个组件是一个元素,它通过action dispatch使用所选对象的id进行更新。我不明白为什么它不会更新元素,即使我可以确认,当我将id作为属性传递时,操作将记录id 我的代码沙盒链接在这里: 元素是Javascript 我的元素赢了';t在我的鼓应用程序中更新动作分派后的显示,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我正在构建一个React/Redux drum应用程序,我需要使用的最后一个组件是一个元素,它通过action dispatch使用所选对象的id进行更新。我不明白为什么它不会更新元素,即使我可以确认,当我将id作为属性传递时,操作将记录id 我的代码沙盒链接在这里: 元素是{display} 行动是 export const drumHit = (url, id) => { const sound = new Audio(url); sound.play(); console
{display}
行动是
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;
}
};
如果您有任何帮助,我们将不胜感激。来自沙盒:
const mapDispatchToProps = dispatch => ({
switcheroo: val => dispatch(switcheroo(val)),
drumHit: id => dispatch(drumHit(id))
});
您没有在mapDispatchToProps
中为drumHit()
操作提供url
参数,因此定义中的第二个参数id
将接收未定义的
此外,您的handleKeyPress
方法:
handleKeyPress = event => {
const drumKey = drumObj.find(obj => obj.keyCode === event.keyCode);
if (drumKey) {
drumHit(drumKey.url, drumKey.id);
}
};
直接使用导入的drumHit
,而不是从this.props
,这意味着该操作实际上不会为您的减速机分派。这就是为什么当您通过按键播放时,url
和id
都被传递时,console
会显示预期的id
编辑:
您的MapStateTrops
正在使用state.id
,但您的减速器正在将id
设置为显示
,因此您只需将其更改为:
const mapStateToProps = state => ({
value: state.value,
url: state.url,
display: state.display
});
我改变了这两件事,显示元素仍然没有改变。我保存了沙盒,我遗漏了什么?而且,我认为这就是这样做的目的:const{value,switchero,drumHit,display}=this.props
但是现在它说drumHit已经定义了,但是从来没有使用过。您在回调中使用drumHit时,使用它是很好的,因为它来自于这个。非常感谢道具!