Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react-router-redux routeActions?

I'm trying to modify the example code of react-router-redux. https://github.com/rackt/react-router-redux/blob/master/examples/basic/components/Home.js

this is my Home.js

class Home extends Component {
    onSubmit(props) {
        this.props.routeActions.push('/foo');    
    }
}

I also have a mapDispatchToProps for it.

function mapDispatchToProps(dispatch){
    return bindActionCreators({ routeActions },dispatch);
}

When i called onSubmit function, I got an error

Uncaught TypeError: this.props.routeActions.push is not a function

If i remove this.props in onSubmit, the key in the URL changed but its still on the same page. From localhost:8080/#/?_k=iwio19 to localhost:8080/#/?_k=ldn1ew

Anyone know how to fix it? Appreciate it.

like image 337
JAckWang Avatar asked Feb 04 '16 09:02

JAckWang


People also ask

Does Redux work with react router?

You can use the connected-react-router library (formerly known as react-router-redux ). Their Github Repo details the steps for the integration. Once the setup is complete, you can now access the router state directly within Redux as well as dispatch actions to modify the router state within Redux actions.

How do you use createBrowserHistory in react?

Import creatBrowserHistory with curly brackets. It's exported as a named export. // history. js import { createBrowserHistory } from "history"; export default createBrowserHistory();


2 Answers

I don't think routeActions are passed as props. What you want to do is this:

import { routeActions } from 'react-router-redux'

this.props.dispatch(routeActions.push('/foo'));
like image 85
jjordy Avatar answered Oct 13 '22 00:10

jjordy


To provide a little more explicit answer and the answer to my own question in the comment.

Yes you can do

import { routeActions } from 'react-router-redux'

this.props.dispatch(routeActions.push('/foo));

However as I mentioned mapDispatchToProps will override this. To fix this you can bind the routeActions like so:

import { bindActionCreators } from 'redux'
import { routeActions } from 'react-router-redux'

function mapDispatchToProps(dispatch) {
    return {
        routeActions: bindActionCreators(routeActions, dispatch),
    }
}

export default connect(null, mapDispatchToProps)(YourComponent)

Now you can do: this.props.routeActions.push('/foo')

Just FYI this can be done even neater

function mapDispatchToProps(dispatch) {
    return {
        ...bindActions({routeActions, anotherAction}, dispatch)
    }
}
like image 32
Michiel Avatar answered Oct 13 '22 00:10

Michiel