【发布时间】:2018-08-25 17:27:37
【问题描述】:
我遇到了 react-redux 动作创建问题。当我在生命周期方法 componentDidMount() 中记录道具时,我的道具是一个空对象
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchSurveys } from '../../actions/index';
export class SurveyList extends Component {
componentDidMount() {
console.log(this.props);
this.props.fetchSurveys();
}
renderSurveys() {
return (
this.props.surveys.length &&
this.props.surveys.map(survey => {
return (
<div className="card blue-grey darken-1" key={survey._id}>
<div className="card-content">
<span className="card-title">{survey.title}</span>
<p>{survey.body}</p>
<p className="right">
Sent On: {new Date(survey.dateSent).toLocaleDateString()}
</p>
</div>
<div className="card-action">
<a>Yes: {survey.yes}</a>
<a>No: {survey.no}</a>
</div>
</div>
);
})
);
}
render() {
return <div>{this.renderSurveys()}</div>;
}
}
function mapStateToProps({ surveys }) {
return { surveys };
}
export default connect(mapStateToProps, { fetchSurveys })(SurveyList);
现在根据 react-redux 文档,默认 dispatch 包含在 props 中,因此我们不需要在 connect 方法中显式调用 mapDispatchToProps 来访问我们的动作创建者。 fetchSurveys() 是一个动作创建者,我希望它返回一个我然后呈现的调查列表。
然而 this.props = {};所以我当然不能在 renderSurveys() 的 undefined 上调用 .map,因为我也没有在 props 上获得调查属性。
我真的很困扰为什么我的道具是空的。任何人都可以对这个问题有所了解,我将非常感激。我尝试使用 bindActionCreators 并拥有自己的 mapDispatchToProps 方法,这也不起作用。
这是我的行动。
import axios from 'axios';
import { FETCH_USER, FETCH_SURVEYS } from './types';
export const fetchUser = () => async dispatch => {
const res = await axios.get('/api/current_user');
dispatch({ type: FETCH_USER, payload: res.data });
};
export const handleToken = token => async dispatch => {
const res = await axios.post('/api/stripe', token);
dispatch({ type: FETCH_USER, payload: res.data });
};
export const submitSurvey = (values, history) => async dispatch => {
const res = await axios.post('/api/surveys', values);
history.push('/surveys');
dispatch({ type: FETCH_USER, payload: res.data });
};
export const fetchSurveys = () => async dispatch => {
console.log('called');
const res = await axios.get('/api/surveys');
dispatch({ type: FETCH_SURVEYS, payload: res.data });
};
我的调查减少器 -
import { FETCH_SURVEYS } from '../actions/types';
export default function(state = [], action) {
switch (action.type) {
case FETCH_SURVEYS:
return action.payload;
default:
return state;
}
}
组合减速机-
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import { reducer as reduxForm } from 'redux-form';
import surveysReducer from './surveysReducer';
export default combineReducers({
auth: authReducer,
form: reduxForm,
surveys: surveysReducer
});
【问题讨论】:
-
this.props.dispatch(fetchSurveys()是文档的意思。dispatch不会自动连接,除非您使用bindActionCreators。您可能还需要默认surveys为[]。 -
@Davin Tryon 根据github.com/reactjs/react-redux/blob/master/docs/api.md#examples :“如果您不提供自己的 mapDispatchToProps 函数或充满动作创建者的对象,则默认的 mapDispatchToProps 实现只会将调度注入组件的道具。”
标签: reactjs react-redux redux-thunk