开发者问题收集

TypeError:map 不是一个函数(使用 React.js)

2021-05-19
1658

我在尝试映射位于 mongo db 集合中的 json 对象内的数组时遇到一些问题。所有模式数据都通过状态传递,并且可以在我正在尝试映射问题数组的页面上使用。

首先,关于如何访问问题数组中的问题以及如何映射数组内容的任何帮助都将不胜感激。

Db 模式

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

后端控制器

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 });
    }
}

前端操作

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 组件

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;

在此处输入图片描述

1个回答

这意味着,当您对 questions 执行 map 时,它还不是一个数组,您可以尝试这个技巧:

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

这将在对 questions 执行 map 之前检查它是否已定义

VersifiXion
2021-05-19