我正在尝试使用mapstatetoprops将数据传递到组件中。问题是数据是从后端提取到减速器中的,但是在我的组件中,我得到了一个空的Array [],随后出现未定义的错误
当我从后端断开连接并将数据放置在reducer内时,一切正常,但是一旦我重新连接到Redux,数据就不会超出Reducer(我正在使用MERN堆栈)
My Reducer
const initialState = {
quizes : [ ]
loading: false
}
export default function(state=initialState,action){
switch(action.type){
case GET_QUIZ:
//The result of the
log below successfully gives
me back data fetched from the API/backend//
console.log(action.payload)
return{
...state,
quizes:action.payload,
loading:false
}
case QUIZ_LOADING:
return{
...state,
loading:true
}
default:
return state;
}
}
.................................................................
my App
class QuestionApp extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
questionId: 1,
question: '',
answerOptions: [],
answer: '',
answersCount: {
Smart: 0,
Subpar: 0,
Confused: 0
},
result: ''
};
this.handleAnswerSelected = this.handleAnswerSelected.bind(this);
}
componentDidMount() {
this.props.getQuiz();
//The result of the log beow gives me back an empty Array//
console.log(this.props.quiz.quizes)
const shuffledAnswerOptions = this.props.quiz.quizes.map((question) =>
this.shuffleArray(question.answers));
this.setState({
// the error appears on next line : Uncaught TypeError: Cannot read property 'question' of undefined
question: this.props.quiz.quizes[0].question,
answerOptions: shuffledAnswerOptions[0]
});
}
//Remaining body of code
QuestionApp.propTypes ={
getQuiz:PropTypes.func.isRequired,
quiz:PropTypes.object.isRequired
}
const mapStateToprops=(state)=>({
quiz: state.quiz
});
export default connect(mapStateToprops,
{getQuiz})(QuestionApp)
...................................................................
CombineReducer
export default combineReducers({
quiz:quizReducer,
user: userReducer
});
sample of the Data = quizes:[]
[
{
question: "What is 4 X 4 ? ",
answers: [
{ type: "Smart",content: "16" },
{
type: "Subpar",
content: "15"
},
{
type: "Confused",
content: "1"
}
]
},
.......................................................................
My Schema
const QuizSchema = new Schema({
question: {
type:String,
default:''
},
answers: [{
type: {
type: String,
default:''
},
content: {
type: String,
default:''
},
}]
});
module.exports=Quiz=mongoose.model('quizes',QuizSchema,'quiz');