未处理的拒绝(TypeError):this.props.dispatch(...)。则不是函数

时间:2020-07-18 19:15:08

标签: reactjs redux react-redux redux-thunk redux-promise-middleware

我正在一起使用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/nTnv9khhttps://prnt.sc/tkcs0m

(未处理的拒绝(TypeError):this.props.dispatch(...)。则不是函数 )

如果我在ComponentDidMount中不使用.then(),那么我将变得不确定。另外,如果我通过添加.then()在AXIOS请求中调度,这是我得到的另一个错误

(错误:操作必须是普通对象。对异步操作使用自定义中间件。) https://imgur.com/a/czlvHBjhttps://prnt.sc/tkcsqy

2 个答案:

答案 0 :(得分:0)

在向axios调用添加异步等待之后,它起作用了(我认为应该由中间件处理),但是现在我的Header组件出现了另一个错误

    useEffect(() => {
        
        props.dispatch(actions.authUser()).then(() => {
            console.log(props, actions)
            if(props.user.isAuth) setToggleLogOut(true)
        })

        window.addEventListener('scroll', ()=> {
            window.scrollY > 0 ? setToggleHeader(true) : setToggleHeader(false)
        });
    }, [props.value])

    const handleLogOut = () => {
        props.logOutUser(() => {
            setToggleLogOut(false)
        })
    }


.
.
.
.
.
.
.
.


function mapStateToProps (state) {
    return {
        user: state.user.userData
    }
}

export default connect(mapStateToProps)(Header)                                                                                                     

(未处理的拒绝(TypeError):无法读取未定义的属性'isAuth') https://prnt.sc/tkd0bj

答案 1 :(得分:0)

问题1:问题出在您的axios呼叫中。 enter link description here阅读文档。 axios get返回承诺。使用可以使用try catch或async await。

问题2:

const authData = useSelector(state => state.user)
const [isLoading, setIsLoading] = useState(true)

useEffect(() => {
   if(authData.isAuth) {
      setIsLoading(false)
   }

}, [authData]);

if(isLoading) return <p>loading...</p>

// your rest of code
相关问题