我在react 中创建了一个新组件
import React, {FC, useEffect} from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { fetchExternalLinks } from '../../redux/reducers/appReducer'
import { getExternalLinksSelector } from '../../redux/selectors/appSelector'
type LinksType = {
title?: string | undefined
}
const ExternalLinks : FC<LinksType> = (props) => {
const {
title
} = props
const dispatch = useDispatch()
const links = useSelector(getExternalLinksSelector)
useEffect(() => {
console.log('use effect')
dispatch(fetchExternalLinks)
})
const openWindow = (path: string) => {
window.open(path, '_blank', 'toolbar=0,location=0,menubar=0');
}
return (
<>
Links:
{links.map((link) => {
return <a onClick={() => openWindow(link.path)}>{link.title}</a>
})
}
</>
)
}
export default ExternalLinks
当我尝试用dispatch从reducer调用fetchExternalLinks方法时,它不起作用。
在我的控制台上,我只能看到";使用效果";,但还原剂没有
export const fetchExternalLinks = (): ThunkType => async (dispatch) => {
console.log("test")
try {
dispatch(appActions.toggleIsFetching(true))
const response = await appApi.getCustomers()
dispatch(appActions.setExternalLinks(response.data))
} catch (e) {
dispatch(appActions.toggleResponseMessage({isShown: true, isSuccess: false}))
} finally {
dispatch(appActions.toggleIsFetching(false))
}
}
更改您的代码,
dispatch(fetchExternalLinks)
对此,
dispatch(fetchExternalLinks())
由于您只传递引用,所以您的异步thunk不会被执行,当使用((而不是传递引用来调用fetchExternalLinks函数时,您将收到一个箭头函数作为返回值,react redux将传递调度函数并为您执行