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

J S*_*olt 5 reactjs react-router-dom

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

handleSubmit(e) {
    e.preventDefault(); 
    this.props.dispatch(loginUser({
        username: this.state.username, 
        password: this.state.password, 
        history: this.props.history
    }));
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我将 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}`)); 
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 3

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

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