[英]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.