简体   繁体   English

为什么我在控制台中未定义,当我尝试使用 typescript 订阅和使用我的上下文并做出反应时

[英]Why am i getting undefined in my console, when i try to subscribe and use my context using typescript and react

When trying to create a simple quiz app without the need to prop drilling I've stumbled upon an issue while trying to integrate context into the project.在尝试创建一个简单的测验应用程序而无需支撑钻探时,我在尝试将上下文集成到项目中时偶然发现了一个问题。 The issue is that when subscribing to my context as shown below and console.问题是当订阅我的上下文时,如下所示和控制台。 logging 'name', I get the value of undefined.记录“名称”,我得到未定义的值。 What am I missing in order to get my name(stored in a state in my context) logged instead of getting undefined?为了让我的名字(存储在我的上下文中的 state 中)而不是未定义,我缺少什么?

My context我的背景

import React, { createContext, Dispatch, SetStateAction, useContext, useState } from 'react';

export interface IUserContextType {
  name: string;
  test: string;
  setName: Dispatch<SetStateAction<string>>;
  setTest: Dispatch<SetStateAction<string>>;
}

type IQuizContextProvidorProps = {
  children: React.ReactNode;
};

export const QuizContext = createContext({} as IUserContextType);

export const useQuizContext = () => useContext(QuizContext);

const QuizContexProvider = ({ children }: IQuizContextProvidorProps) => {
  const [name, setName] = useState('Marvin');
  const [test, setTest] = useState('This is a test');
  const values = { name, test, setName, setTest };

  return <QuizContext.Provider value={values}>{children}</QuizContext.Provider>;
};

export default QuizContexProvider;

My App我的应用

import { useState } from 'react';
import './App.css';
import quizApi from './utils/quiz.json';
import { IQuiz, IQuizAnswers } from './model/IQuiz';
import { Button, LinearProgress, Paper, styled, Typography } from '@mui/material';
import { Box } from '@mui/system';
import QuizContexProvider, { useQuizContext } from './utils/QuizContex';

const QuizContainer = styled(Box)(({ theme }) => ({
  '.correct': {
    backgroundColor: 'darkseagreen',
  },
  '.linearProgress': {
    height: '1rem',
  },
}));

function App() {
  const { name, test } = useQuizContext();
  console.log('name', name);

  function shuffle(array: Array<any>) {
    return array.sort(() => Math.random() - 0.5);
  }

  const quiz: Array<IQuiz> = shuffle(quizApi);

  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [progress, setProgress] = useState(0);
  const [viewQuiz, setViewQuiz] = useState(true);
  const [quizScore, setQuizScore] = useState(0);

  const inkrementWith = 100 / quiz.length;

  const handleProgress = () => {
    setProgress(progress + inkrementWith);
  };

  const handleAnswer = (answers: IQuizAnswers) => {
    const nextQuestion = currentQuestionIndex + 1;
    handleProgress();

    if (nextQuestion < quiz.length) {
      setCurrentQuestionIndex(nextQuestion);
    } else {
      setViewQuiz(false);
    }

    if (answers.isTrue === true) {
      setQuizScore(quizScore + 1);
    }
  };

  const handleReset = () => {
    setCurrentQuestionIndex(0);
    setProgress(0);
    setQuizScore(0);
    setViewQuiz(true);
  };
  return (
    <QuizContexProvider>
      <QuizContainer className='App'>
        <Box component='header' className='App-header'>
          {viewQuiz ? (
            <>
              <Box sx={{ width: '50%' }}>
                <LinearProgress className='linearProgress' variant='determinate' color='success' value={progress} />
              </Box>

              {quiz.map(
                (question, index) =>
                  index === currentQuestionIndex && (
                    <Box key={index}>
                      <Box>{question.questionLabel}</Box>
                      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem', margin: '1rem' }}>
                        {shuffle(question.answerOptions).map((answers, index) => (
                          <Paper
                            key={index}
                            onClick={() => {
                              return handleAnswer(answers);
                            }}
                            component='button'
                          >
                            {answers.answerLabel}
                          </Paper>
                        ))}
                      </Box>
                    </Box>
                  )
              )}
            </>
          ) : (
            <Paper>
              <Typography component='h1' variant='h3'>
                Quiz results
              </Typography>
              <Typography component='h2' variant='subtitle1'>
                Quiz results
              </Typography>

              <Typography component='h1' variant='h1' sx={{ fontWeight: 700 }}>
                {quizScore} / {quiz.length}
              </Typography>
              <Button variant='contained' onClick={handleReset} sx={{ margin: '1rem 0rem' }}>
                Reset quiz
              </Button>
            </Paper>
          )}
        </Box>
      </QuizContainer>
    </QuizContexProvider>
  );
}

export default App;

Any component that wish to use context value, should be wrapped inside the provider.任何希望使用上下文值的组件都应包装在提供程序中。 Your <App /> component is using context value, so it should be:您的<App />组件正在使用上下文值,因此它应该是:

<QuizContexProvider>
  <App />
</QuizContexProvider>

You can put the provider in Index.ts file.您可以将提供程序放在Index.ts文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的控制台上未定义? - Why am I getting undefined on my console? 当我尝试使用 children 属性和 offsetWidth 时,为什么在我的控制台中收到无法读取属性消息? - Why am I getting a cannot read property message in my console when I try to use children property and offsetWidth? 当我尝试调用我的函数时,为什么会出现“未定义”? - Why am I getting an 'undefined' when I try to call my function? 当我尝试使用map()时,为什么我的GET响应未定义 - Why is my GET response undefined when I try to use map() 当我尝试运行我的 React 项目时出现错误 - I am getting an error when I try to run my react project 当我尝试使用“npm i react-bootstrap”安装 React-Bootstrap 时,为什么会出现“无法读取未定义的属性‘长度’”错误? - Why am I getting a "Cannot read property 'length' of undefined" error when I try to install React-Bootstrap using "npm i react-bootstrap"? 为什么我在 React 中的锚标记上的 onClick 事件中未定义? - Why am I getting undefined from my onClick event on my anchor tag in React? 当我尝试调用我的方法时,为什么我会变得不确定? - Why am I getting undefined when I am trying to call my method? 当我尝试设置我的收藏夹图标时,为什么会出现 [object HTMLImageElement]? - Why am I getting [object HTMLImageElement] when I try to set my favicon? 当我尝试更改我的 Discord 头像时,为什么会收到“400:错误请求”? - Why am I getting a '400: Bad Request' when i try to change my Discord avatar?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM