【问题标题】:Function is not getting called anymore, when trying to dispatch a type尝试分派类型时不再调用函数
【发布时间】:2021-03-31 09:15:55
【问题描述】:

我目前正在尝试使用 Spotify API 访问我的数据。这很好用。这就是我用来获取数据的功能。我认为其他的东西并不重要。如果你需要,我可以发布。

export const getSpotifyUser = (access_token:string) =>{
     setAuthorizationHeader(access_token)
     axios.get('https://api.spotify.com/v1/me').then((res) => {
      console.log(res.data)
    })
  } 

我已经建立了一个 redux 存储并尝试通过调度正确的类型 (SET_USER) 将凭据放入存储中。

 export const getSpotifyUser = (access_token:string) => (dispatch: any) => {
console.log("function is not called") // Function is not even called why ?
         setAuthorizationHeader(access_token)
         axios.get('https://api.spotify.com/v1/me').then((res) => {
          console.log(res.data)
    dispatch ({
    type: SET_USER,
    payload: res.data
        })
      } 

但是一旦我使用了 dispatch,这个函数就不再被调用了。 我真的没有看到我的错误。那是打字稿错误吗? (我正在使用反应打字稿)

store.js

import { createStore, applyMiddleware } from 'redux'
import rootReducer from './rootReducer'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
)

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
export default store

rootReducer.ts

 import { combineReducers } from 'redux'
    import userReducer from './User/userReducer'
    
    const rootReducer = combineReducers({
      user: userReducer,
    })
    
    export default rootReducer

userReducer.ts

 import { AnyAction } from 'redux'

import { SET_USER } from './userTypes'

interface Credentials {
  username: string
  email: string
  profilepicture: string
  id: number
}

interface InitialState {
  authenticated: boolean
  loadding: boolean
  credentials?: Credentials
}

const initialState: InitialState = {
  authenticated: false,
  loadding: false,
  credentials: {} as Credentials,
}

const reducer = (state = initialState, action: AnyAction)  => {
  switch (action.type) {
    case SET_USER: {
      return {
        ...state,
        loading: false,
        credentials: action.payload,
      }
    }
    default:
      return state
  }
}

export default reducer

Login.tsx(我在这里登录。它工作正常,如果不使用调度

 import {  IonButton } from '@ionic/react'
    
    import React, { useEffect } from 'react'
    
   
    import {
      getAuthorizeHref,
      getHashParams,
      removeHashParamsFromUrl,
      getSpotifyUser,
    } from '../../Helpers/login'
    
           const Login: React.FC = () => {
      // const user = useSelector((state: RootState) => state.user.credentials)
    
      useEffect(() => {
        const hashParams = getHashParams()
        const access_token = hashParams.access_token
        // const expires_in = hashParams.expires_in
        removeHashParamsFromUrl()
      
        getSpotifyUser(access_token)
      }, [])
    return (
      <IonButton onClick={() => window.open(getAuthorizeHref(), '_self')}>
    )}
    export default Login

【问题讨论】:

  • 你的编译器告诉你什么?我不知道 redux,但我很确定你的 dispatch 参数不应该放在这里,那是错误的语法。据我了解,您应该在对象上调用 dispatch 方法。
  • 你确定吗?这就是我学到的方式。我没有使用 dispatch Hook 来明确。 youtu.be/m_u6P5k0vP0?t=22935 。例如,他也在这样做
  • 能否请您发布您的意思的代码? :)
  • 好吧,实际上语法是错误的,你忘了第二个 => 箭头函数 man。但是你应该有一个编译器来告诉你,或者至少记录你的打字稿错误。
  • 哦,对不起,我刚刚删除了第二个 =>,而我正在写我的帖子

标签: javascript reactjs typescript react-redux


【解决方案1】:

由于您使用带有 react 的 typescript,我相信您已将 getSpotifyUser 函数添加到您的界面中,现在如果您想访问它,我认为您应该这样称呼它

props.getSpotifyUser(access_token)

最后将它作为包装组件的调度函数添加到您的连接中

你的登录组件应该是这样的

import {  IonButton } from '@ionic/react'
    
import React, { useEffect } from 'react'

import { connect } from 'react-redux'

import {
  getAuthorizeHref,
  getHashParams,
  removeHashParamsFromUrl,
  getSpotifyUser,
} from '../../Helpers/login'

interface ILogin {
  getAuthorizeHref: () => any;
  getHashParams: () => any;
  removeHashParamsFromUrl: () => any;
  getSpotifyUser: (access_token) => any;
}

const Login: React.FC = (props: ILogin) => {
  // const user = useSelector((state: RootState) => state.user.credentials)

  useEffect(() => {
    const hashParams = props.getHashParams()
    const access_token = hashParams.access_token
    // const expires_in = hashParams.expires_in
    props.removeHashParamsFromUrl()
  
    props.getSpotifyUser(access_token)
  }, [])
return (
  <IonButton onClick={() => window.open(props.getAuthorizeHref(), '_self')}>
)}
export default connect(null, {getAuthorizeHref, getHashParams, removeHashParamsFromUrl, getSpotifyUser})(Login)

【讨论】:

  • 不,我没有在我的界面中添加 getSpotifyUser。我不需要这样做。这些功能运行良好,直到我使用 (dispatch: any) => ...
  • 也许我错了,看不到我的错误。你能发布你真正想要的代码吗?
  • 在您将调度附加到它之前,该函数工作正常?
  • useDispatch() 是更好的选择,但我也没有使用那个钩子。我正在传递一个正在分派类型的异步函数:该函数甚至没有被调用。也在你的方法中
  • 任何使用该调度的函数都是一个 redux 操作,您必须专门按照文档来调用该函数,如果您不这样做,该函数将不会被调用
【解决方案2】:

基本上,Shamim 给出了正确的答案。任何使用该调度的函数都是一个 redux 操作,您必须专门按照文档来调用该函数。您必须使用 connect 来调度操作。作为替代方案,您可以使用 dispatchHook。如有错误请指正!!!!

这是正确的代码,我只需要更正 Login.tsx

import { IonApp, IonButton } from '@ionic/react'

import React, { useEffect } from 'react'
import { connect } from 'react-redux'

import {
  getAuthorizeHref,
  getHashParams,
  removeHashParamsFromUrl,
  getSpotifyUser,
} from '../../Helpers/login'

const style = {
  Logo: {
    display: 'flex',
    justifyContent: 'space-evenly',
    color: 'white',
    position: 'relative',
    top: '70%',
  } as const,
}

const Login: React.FC = (props: any) => {
  // const user = useSelector((state: RootState) => state.user.credentials)

  useEffect(() => {
    const hashParams = getHashParams()
    const access_token = hashParams.access_token
    // const expires_in = hashParams.expires_in
    removeHashParamsFromUrl()
    console.log('halloeuseeffect')
    props.getSpotifyUser(access_token)
    console.log('halloeuseeffect')
  }, [])

  return (
    <IonApp>
      
     
          <IonButton onClick={() => window.open(getAuthorizeHref(), '_self')}>
            knsnan
        
    </IonApp>
  )
}

export default connect(null, {
  getSpotifyUser,
})(Login)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 2013-01-28
    • 2015-01-17
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多