JAc*_*ang 7 reactjs react-router react-router-redux
我正在尝试修改react-router-redux的示例代码. https://github.com/rackt/react-router-redux/blob/master/examples/basic/components/Home.js
这是我的Home.js
class Home extends Component {
onSubmit(props) {
this.props.routeActions.push('/foo');
}
}
Run Code Online (Sandbox Code Playgroud)
我也有一个mapDispatchToProps.
function mapDispatchToProps(dispatch){
return bindActionCreators({ routeActions },dispatch);
}
Run Code Online (Sandbox Code Playgroud)
当我调用onSubmit函数时,我收到了一个错误
Uncaught TypeError: this.props.routeActions.push is not a function
Run Code Online (Sandbox Code Playgroud)
如果我在onSubmit中删除this.props,则URL中的键已更改,但它仍在同一页面上.从localhost:8080/#/?_k=iwio19到localhost:8080/#/?_k=ldn1ew
谁知道怎么修它?欣赏它.
小智 9
我不认为routeActions是通过的props.你想要做的是:
import { routeActions } from 'react-router-redux'
this.props.dispatch(routeActions.push('/foo'));
Run Code Online (Sandbox Code Playgroud)
小智 9
在评论中提供一个更明确的答案和我自己的问题的答案.
是的,你可以做到
import { routeActions } from 'react-router-redux'
this.props.dispatch(routeActions.push('/foo));
Run Code Online (Sandbox Code Playgroud)
但是正如我所提到的,mapDispatchToProps会覆盖它.要修复此问题,您可以像这样绑定routeActions:
import { bindActionCreators } from 'redux'
import { routeActions } from 'react-router-redux'
function mapDispatchToProps(dispatch) {
return {
routeActions: bindActionCreators(routeActions, dispatch),
}
}
export default connect(null, mapDispatchToProps)(YourComponent)
Run Code Online (Sandbox Code Playgroud)
现在你可以这样做: this.props.routeActions.push('/foo')
仅供参考,这可以做得更整齐
function mapDispatchToProps(dispatch) {
return {
...bindActions({routeActions, anotherAction}, dispatch)
}
}
Run Code Online (Sandbox Code Playgroud)
至于react-router-redux v4:
import { push } from 'react-router-redux';
export class ExampleContainer extends React.Component {
static propTypes = {
changeRoute: React.PropTypes.func,
};
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url)),
dispatch,
};
}
}
export default connect(null, mapDispatchToProps)(ExampleContainer);
Run Code Online (Sandbox Code Playgroud)
然后:
this.props.changeRoute('/foo');
Run Code Online (Sandbox Code Playgroud)
小智 5
通过这样做,我能够让它发挥作用
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { routeActions } from 'react-router-redux'
export const Cmpt = React.createClass({ //code })
function mapDispatchToProps(dispatch) {
return bindActionCreators({
push: routeActions.push,
//all your other action creators here
}, dispatch)
}
export const CmptContainer = connect({}, mapDispatchToProps)(Cmpt)
Run Code Online (Sandbox Code Playgroud)
然后你可以使用push via道具
this.props.push('some/cool/route')
| 归档时间: |
|
| 查看次数: |
13777 次 |
| 最近记录: |