// 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开发工具选项卡:一个数组与几个条目。但当控制台。登录我的Calendar组件,它返回一个未定义结果的promise:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
我做错了什么?
通常您希望在组件中访问Redux的分派或存储。您已经在组件中拥有了分派函数,但是如果您需要访问其中的Redux状态:
首先,您需要定义这样的函数,它使redux存储在组件中可用。
const mapStateToProps = (state) => ({
state: state // a "state" prop is available in the component which points to redux state,
})
或者您可以自定义它,如果您只需要Redux状态的某些属性:
const mapStateToProps = (state) => ({
state: state.event //
})
,然后像这样修改连接函数:
connect(mapStateToProps)(Calendar)