解决方案是从这里改编的:
addEventListener 使用映射调度对 redux 做出react
关键是删除 jquery 并使用 document.addEventListener 将其绑定到 react 组件中。这是工作代码的摘录:
////////////////////////////////////////////
////////////////////// containers
////////////////////////////////////////////
class GameMap extends React.Component{
renderMap(){
console.log('renderMap')
console.log(this.props)
return this.props.gamemap.map((tile) => {
//const x = "tile " + tile
return <div className={"tile " + tile}></div>
})
}
render() {
console.log('GameMap.render()')
return (
<div className="GameMap">
{this.renderMap()}
</div>)
}
componentDidMount() {
console.log("componentDidMount")
console.log(this)
// the following line won't be bound to the store here...
document.addEventListener("keydown", this.props.keyPress );
}
}
function GMmapStateToProps(state){
//from here goes into this.props
console.log('BLmapStateToProps')
console.log(state)
const gamemap = state.gamemap.gamemap.map((a) => {
switch (a){
case 1:
return "tile-free"
case 9:
return "tile-user"
}
return "tile-wall"
})
return{
gamemap: gamemap
}
}
function GMmapDispatchToProps(dispatch){
//when selectbook called, pass result to all reducers
console.log('GMmapDispatchToProps')
return bindActionCreators({keyPress: keyPress}, dispatch)
}
const VGameMap = connect(GMmapStateToProps, GMmapDispatchToProps)(GameMap)
////////////////////////////////////////////
////////////////////// actions
////////////////////////////////////////////
// actions/index.js action creator
function keyPress(key) {
console.log('keyPress: ', key)
console.log(key.key)
var vector = ""
switch(key){
case 'w', 'ArrowUp':
vector = {x:0,y:1}
case 's', 'ArrowDown':
vector = {x:0,y:-1}
case 'a', 'ArrowLeft':
vector = {x:-1,y:0}
case 'd', 'ArrowRight':
vector = {x:1,y:0}
}
return {
type: "KEYPRESS",
payload: vector
} // this is an action created
}