简体   繁体   English

React/Redux - 将 this.props.history 传递给 thunk 是一种反模式吗?

[英]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.当表单提交时,它会触发一个 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.如您所见,我将 react-router-dom 的历史传递给 thunk。 Here is the thunk:这是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.根据此页面: https : //reacttraining.com/react-router/web/guides/redux-integration您正在做正确的事情,包括您的 thunk 输入中的历史记录。

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."引用:“这里的解决方案只是在操作的有效负载中包含历史对象(提供给所有路由组件),并且您的异步处理程序可以在适当的时候使用它进行导航。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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