繁体   English   中英

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

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

我在一个简单的反应应用程序中有一个表单。 当表单提交时,它会触发一个 thunk。

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

如您所见,我将 react-router-dom 的历史传递给 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}`)); 
}

如您所见,如果获取成功,我将推送到历史记录。

这是一种反模式吗? 或者这可以。 它有效*但我想知道它是否超级奇怪/不推荐

根据此页面: https : //reacttraining.com/react-router/web/guides/redux-integration您正在做正确的事情,包括您的 thunk 输入中的历史记录。

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

暂无
暂无

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

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