我在一个简单的反应应用程序中有一个表单。当表单提交时,它会触发一个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输入中的历史。
引用:“这里的解决方案只是在操作的有效负载中包含历史对象(提供给所有路由组件),并且异步处理程序可以在适当的时候使用它来导航。”