gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:18:18 25 4
gpt4 key购买 nike

我在一个简单的 react 应用程序中有一个表单。当表单提交时,它会发出一声重击。

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

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

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

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

最佳答案

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

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

关于reactjs - React/Redux - 将 this.props.history 传递给 thunk 是反模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com