简体   繁体   中英

React/Redux - Is passing this.props.history to a thunk an anti-pattern?

I have a form in a simple react app. When the form submits, it fires a thunk.

handleSubmit(e) {
    e.preventDefault(); 
    this.props.dispatch(loginUser({
        username: this.state.username, 
        password: this.state.password, 
        history: this.props.history
    }));
}

As you can see, I am passing react-router-dom's history to the thunk. Here is the thunk:

export const loginUser = input => dispatch => {
    return fetch('xxxxxxxxxx', {
        method: 'POST', 
        body: JSON.stringify({
            username: input.username, 
            password: input.password
        }), 
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(res => {
        if(!res.ok) {
            return Promise.reject(res.statusText)
        }
        return res.json(); 
    })
    .then(token => {
        localStorage.setItem('token', token.authToken); 
        input.history.push('/'); 
    })
    .catch(err => console.error(`error: ${err}`)); 
}

As you can see, if the fetch is successful, I then push to the history.

Is this an anti-pattern? Or is this ok. It works* but I want to know if it's super weird/not recommended

According to this page: https://reacttraining.com/react-router/web/guides/redux-integration you are doing the correct thing including history in your thunk input.

Quote: "The solution here is simply to include the history object (provided to all route components) in the payload of the action, and your async handler can use this to navigate when appropriate."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM