简体   繁体   中英

TypeError: map is not a function (Using React.js)

I am having some issues trying to map an array that sits within a json object in a mongo db collection. All of the schema data is being passed through the state and is available on the page I am tying to map the question array.

Any help on firstly how I can access the questions within the question array and how I can look to map the array contents would be greatly appreaciated.

Db schema

const QuizSchema = mongoose.Schema({
    quizName: String,
    quizTheme: String,
    shortDescription: String,
    longDescription: String,
    question: [{
        question1: String,
        question2: String,
        question3: String,
        question4: String,
        answer: String
    }]
})

back end controller

export const getQuestions = async (req, res) => {
    const { id } = req.params;

    try {
        const questions = await Quiz.findById(id);

        res.status(200).json(questions);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

front end action

export const getQuestions = (id) => async (dispatch) => {
  try {
    dispatch({ type: 'START_LOADING' });

    const { data } = await api.fetchQuestions(id);

    dispatch({ type: 'FETCH_QUESTIONS', payload: data });
    dispatch({ type: 'END_LOADING' });
  } catch (error) {
    console.log(error);
  }
};

reducer

case 'FETCH_QUESTIONS':
      return { ...state, questions: action.payload };

React component

const Questions = () => {
  const { questions, quiz, isLoading } = useSelector((state) => state.quiz);
  const dispatch = useDispatch();
  const classes = useStyles();
  const { id } = useParams();
  console.log(questions)
  useEffect(() => {
    dispatch(getQuestions(id));
  }, [id]);

  if (!questions) return null;


  if (isLoading) {
    return (
      <Paper elevation={6} className={classes.loadingPaper}>
        <CircularProgress size="7em" />
      </Paper>
    );
  }



  return (
    <Paper style={{ padding: '20px', borderRadius: '15px' }} elevation={6}>
      <div className={classes.card}>
        <div className={classes.section}>
          <Typography variant="h3" component="h2">{questions.quizName}</Typography>
          <Typography gutterBottom variant="body1" component="p">{questions.quizTheme}</Typography>
          <Typography variant="body1">{questions.longDescription}</Typography>
          <Divider style={{ margin: '20px 0' }} />
          <Typography variant="body1"><strong>Questions</strong></Typography>
          <Divider style={{ margin: '20px 0' }} />
          {questions.map((question) => (
            <Card elevation={6}>
              <Grid>
                <p>{question.question1}</p>
              </Grid>
            </Card>
          ))}
        </div>
      </div>
    </Paper>
  );
};

export default Questions;

在此处输入图像描述

This means questions is not an array yet when you do the map on it, you can try this trick:

{questions && questions.map((question) => (
            <Card elevation={6}>
              <Grid>
                <p>{question.question1}</p>
              </Grid>
            </Card>
          ))}

This will check if questions is defined before doing the map on it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM