我在组件中时遇到错误,然后点击WeddingList
内部并尝试返回。
基本上流程是:
Wedding Page
页面 - > 点击 - > WeddingList
- &gt; 点击 - &gt; < / strong> this.props.weddings.map
因此,当我点击返回时,会触发此错误:
TypeError:
WeddingList.renderWeddings
不是函数import React, { Component } from 'react'; import { connect } from 'react-redux'; import { fetchWeddings } from '../../actions'; import { Link } from 'react-router-dom'; class WeddingList extends Component { componentWillMount() { this.props.fetchWeddings(); } renderWeddings() { return this.props.weddings.map(wedding => { return ( <div className="row" key = { wedding._id }> <div className="col s10 offset-s1" key={wedding._id}> <div className="card blue-grey darken-1" key={wedding._id}> <div className="card-content white-text"> <span className="card-title">{wedding.coupleName1} & {wedding.coupleName2}</span> </div> <div className="card-action"> <Link to={'/wedding/'+wedding.pageName} className="btn"> Visit! </Link> </div> </div> </div> </div> ); }) } render() { return ( <div> {this.renderWeddings()} </div> ); } } function mapStateToProps({ weddings }) { return { weddings }; } export default connect(mapStateToProps, { fetchWeddings })(WeddingList);
这是我的代码:
WeddingList.js
import React from 'react';
import WeddingPage from './weddings/WeddingPage';
import { Link } from 'react-router-dom';
const Wedding = props => {
return (
<div>
<WeddingPage {...props}/>
<Link to={'/weddings'} className="btn">Back</Link>
</div>
);
}
export default Wedding;
&#13;
Wedding.js
import { FETCH_WEDDINGS, FETCH_WEDDING } from '../actions/types';
export default function(state = [], action) {
switch (action.type) {
case FETCH_WEDDINGS:
return action.payload;
case FETCH_WEDDING:
return action.payload;
default:
return state;
}
}
&#13;
weddingsReducer.js
import { combineReducers } from 'redux';
import { reducer as reduxForm } from 'redux-form'
import authReducer from './authReducer';
import weddingsReducer from './weddingsReducer';
export default combineReducers({
auth: authReducer,
form: reduxForm,
weddings: weddingsReducer,
wedding: weddingsReducer
});
&#13;
reducers.js
{{1}}&#13;
提前致谢
答案 0 :(得分:0)
在第一次渲染中看起来this.props.weddings
是undefined
。如果ajax请求收到婚礼,可能会发生这种情况(fetchWeddings
会这样做)。解决方案是在reducers.js中设置初始状态:
import { FETCH_WEDDINGS, FETCH_WEDDING } from '../actions/types';
const initialState = { weddings: [] }
export default function(state = initialState, action) {
switch (action.type) {
case FETCH_WEDDINGS:
return {...state, weddings: action.payload.weddings};
case FETCH_WEDDING:
return {...state, wedding: action.payload.wedding};
default:
return state;
}
}
此外,您可以在PropTypes
中验证WeddingList.js
:
import PropTypes from 'prop-types';
class WeddingList extends Component {
static propTypes = {
wedding: PropTypes.array.isRequired
}
....
}