为什么状态未定义?[钩子/冗余]



我正在尝试通过钩子使用 Redux,但状态不断返回一个空数组,而不是来自获取请求的数据。

行动

export const loading = payload => {
return {
type: types.LOADING,
payload
}
}
export const getBudget = payload => {
return {
type: types.BUDGET_DATA,
payload
}
}
export const budgetData = () => {
return dispatch => {
dispatch(loading(true))
const url = `${URL_BUDGET}`
fetch(url)
.then(response => dispatch(getBudget(response.data)))
.catch(err => console.log(err))
dispatch(loading(false))
}
}

还原剂

import * as types from '../types'
const initialState = {
budget: []
}
export default (state = initialState, action) => {
switch (action.types) {
case types.BUDGET_DATA:
return {
...state,
budget: action.payload
}
default:
return state
}
}

元件

const Home = () => {
useDispatch(budgetData(), categoryData())
const state = useSelector(state => state.data)
const budgets = useSelector(state => state.data.budget)
const categories = useSelector(state => state.data.category)
//console.log(this.props.dataReducer)
return (
<div>
content
</div>
)
}
export default Home

我似乎无法理解为什么没有满足获取请求。

我的 API 具有以下数据格式...

{"meta":{},"data":{"example":[{"timestamp":28378545,"value":5}],...}}

调度有问题吗?!添加加载也无济于事!

useDispatch返回一个随后需要调用的dispatch函数。如果只想在首次渲染组件时执行此操作一次,则可以将其与没有依赖项的useEffect配对:

const Home = () => {
const dispatch = useDispatch()
const budgets = useSelector(state => state.data.budget)
const categories = useSelector(state => state.data.category)
useEffect(() => {
dispatch(budgetData())
dispatch(categoryData())
}, [])
return (
<div>
content
</div>
)
}
export default Home

相关内容

  • 没有找到相关文章

最新更新