【发布时间】:2020-11-08 08:51:49
【问题描述】:
我同时使用 redux-thunk 和 redux-promise,不知何故 redux-thunk 中间件没有被调用,我得到一个错误。
这是我的设置
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom'
import {Provider} from 'react-redux'
import { composeWithDevTools } from 'redux-devtools-extension';
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import promiseMiddleware from 'redux-promise';
import {ThemeProvider} from "@material-ui/core/styles"
import theme from "./components/ui/Theme"
import reducers from './reducers/index'
import './index.css';
import App from './App';
const middleware =[thunk, promiseMiddleware]
const store = createStore(
reducers,
composeWithDevTools(applyMiddleware(...middleware))
)
ReactDOM.render(
<Provider store={store}>
<ThemeProvider theme={theme}>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
</Provider>
,
document.getElementById('root')
);
这是我的动作创作者
export const authUser = () => {
const res = axios.get("http://localhost:3002/api/users/auth", {withCredentials: true})
return {type: AUTH_USER, payload: res.data}
}
这是我的高阶 AUTH 组件,它根据我想要更改路线的结果呈现另一个组件并在 ComponentDidMount 中调度操作之后。
import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import CircularProgress from '@material-ui/core/CircularProgress';
import {authUser} from '../actions/user'
export default function(WrappedComponent, isRestricted){
class Auth extends React.Component {
state = {
loading: true
}
componentDidMount() {
this.props.dispatch(authUser()).then(() => {
this.setState({loading: false})
// if(!this.props.user.isAuth && isRestricted) {
// this.props.history.push('/joinus')
// }
// else if (this.props.user.isAuth && isRestricted === null) {
// this.props.history.push('/')
// }
})
}
render() {
if(this.state.loading) {
return (
<CircularProgress />
)
}
return (
<div>
<WrappedComponent {...this.props} />
</div>
)
}
}
function mapStateToProps (state) {
return {
user: state.user.userData
}
}
return connect(mapStateToProps)(withRouter(Auth))
}
最后这是我得到的错误。
https://imgur.com/a/nTnv9kh 或 https://prnt.sc/tkcs0m
(Unhandled Rejection (TypeError): this.props.dispatch(...).then 不是函数 )
如果我不在 ComponentDidMount 中使用 .then(),那么我会得到未定义。此外,如果我通过添加 .then() 在 AXIOS 请求内部分派,这是我得到的另一个错误
(错误:操作必须是普通对象。使用自定义中间件进行异步操作。) https://imgur.com/a/czlvHBj 或 https://prnt.sc/tkcsqy
【问题讨论】:
-
你没有通过道具。检查这个reactjs.org/docs/… 使用构造函数。
-
问题不在于调度函数,而是.then()。我应该可以使用它。我的意思是这就是我所期望的:D
-
问题出在您的 axios 调用中。 github.com/axios/axios 阅读文档。 axios get 返回一个承诺。 use 可以使用 try catch 或 async await。
-
不应该由中间件处理吗?它奏效了,但现在我又遇到了一个错误,我认为我学到的这些概念真的错了:(
-
我可以为此投票吗?
标签: reactjs redux react-redux redux-thunk redux-promise-middleware