【发布时间】:2021-09-08 13:37:32
【问题描述】:
// action
export const getEvents = () => async (dispatch) => {
try {
dispatch({ type: GET_EVENTS_REQUEST })
const data = await axios.get('http://localhost:5000/api/schedule').then((response) => response.data)
dispatch({ type: GET_EVENTS_SUCCESS, payload: data })
} catch (error) {
dispatch({
type: GET_EVENTS_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
})
}
}
// reducer
export const getEventsReducer = (state = { event: [] }, action) => {
switch (action.type) {
case GET_EVENTS_REQUEST:
return { loading: true }
case GET_EVENTS_SUCCESS:
return { loading: false, event: action.payload }
case GET_EVENTS_FAIL:
return { loading: false, error: action.payload }
default:
return state
}
}
// and this is how I'm trying to call my action:
import { getEvents } from '../../redux/actions/calendarActions'
class Calendar extends React.PureComponent {
componentDidMount() {
const { dispatch } = this.props
console.log(dispatch(getEvents()))
}
}
export default connect()(Calendar)
// component is much bigger, I only added relevant parts
直到我的 reducer,如果我 console.log 我的数据,它是正确的,以及在我的 redux 开发工具选项卡中:一个包含一些条目的数组。但是当 console.logging 在我的日历组件中时,它会返回一个带有未定义结果的承诺:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
我做错了什么?
【问题讨论】:
-
getEvents确实返回undefined -
你在使用
redux-thunk吗?如果没有,你应该。它是一个中间件,可让您分派异步操作。另外,您没有await调度,所以它当然会返回Promise -
这正是 redux(和一般状态)的工作原理。与您无法通过控制台记录
this.setState的结果相同的方式。相反,更新会触发重新渲染,您可以在其中获取更新后的值作为道具(假设连接正确)。 -
@RonB。等待
dispatch毫无意义,它不会返回任何东西。承诺是因为getEvents是异步的。 -
@RonB。我正在使用 redux-thunk 并将其添加到我的商店中
标签: reactjs react-redux dispatch