我一直在努力解决这个问题,而且似乎找不到其他同样问题的人。我有这个组件和容器是我的开始屏幕,应该在初始路径上呈现。
组件/ DifficultySelection.jsx
import React from 'react';
import PropTypes from 'prop-types';
export default class DifficultySelection extends React.Component{
constructor(props){
super(props);
this.onClick = this.onClick.bind(this);
}
onClick(e){
this.props.onDifficultyClick(e.target.innerHTML);
this.props.history.push("/play");
}
render(){
return (
<div>
<h2>Select your difficulty</h2>
<div>
<h3 onClick={this.onClick}>Easy</h3>
<h3 onClick={this.onClick}>Medium</h3>
<h3 onClick={this.onClick}>Hard</h3>
</div>
</div>
)
}
}
DifficultySelection.propTypes = {
onDifficultyClick: PropTypes.func.isRequired
}
容器/ DifficultySelection.jsx
import DifficultySelection from '../components/DifficultySelection';
import { setBoardSize } from '../actions/actions';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onDifficultyClick: (difficulty) => {
console.log(difficulty);
let boardSize = 8;
if(difficulty === "Medium") boardSize = 12;
if(difficulty === "Hard") boardSize = 15;
if(difficulty === "Extreme") boardSize = 20;
dispatch(setBoardSize(boardSize));
}
}
}
export default withRouter(connect(
null,
mapDispatchToProps
))(DifficultySelection)
下面是我尝试将这些组件分配给路线的地方。这是我收到错误的地方。顺便说一下,我输入的控制台日志显示我正在导入的组件是Route
个函数,其中包含的图像因为它应该是我认为的类。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import reducers from './reducers/reducers';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { HashRouter, Route, Switch } from 'react-router-dom';
import DifficultySelection from './containers/DifficultySelection';
import Board from './containers/Board';
let store = createStore(combineReducers(reducers));
console.log(DifficultySelection.type);
console.log(Board.type);
ReactDOM.render(
<Provider store={store}>
<HashRouter>
<Switch>
<Route exact path="/" component={DifficultySelection}/>
<Route exact path="/play" component={Board}/>
</Switch>
</HashRouter>
</Provider>,
document.getElementById('root'));
registerServiceWorker();
答案 0 :(得分:6)
问题在于:
export default withRouter(connect(
null,
mapDispatchToProps
))(DifficultySelection)
connect
的语法是connect(mapStateToProps, mapDispatchToProps)(component)
将您的通话放在一条线上,可能更容易看到错误:
withRouter(connect(null, mapDispatchToProps))(DifficultySelection)
connect
从未正确使用DifficultySelection
作为句子,这意味着您的文件未返回连接的组件。
只需按如下方式重新排列:
export default connect(null, mapDispatchToProps)(withRouter(DifficultySelection))
或者,正如评论中所建议的,withRouter
可以省略,因为此组件将从Route
接收道具:
export default connect(null, mapDispatchToProps)(DifficultySelection)