为什么 State 是 Undefined?[Hooks/Redux]
2020-02-01
951
我尝试通过钩子使用 Redux,但状态始终返回一个空数组,而不是来自获取请求的数据。
Actions
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))
}
}
Reducer
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
}
}
Component
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}],...}}
调度有问题吗?!添加加载也无济于事!
1个回答
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
Ross Allen
2020-02-01