接收时未定义的反应道具

React props undefined on receiving

我在传递 props 对象时遇到了这个问题,在第二页上它说它是未定义的。我试过如果我在第一页上用 console.log(databaseObject?.points[0].questions) 正确传递它,这就是我想要的,但是当我尝试在第二页接收它总是未定义的。我是不是在收到道具时遗漏了什么?在 console.log(props.questions) 的第二页上,我得到了 'undefined' 和 console.log(Object.values(props.questions)) 我收到类型错误:“无法将未定义或 null 转换为对象”

first.tsx

interface Point {
  details: string,
  id: string,
  image: string,
  imagePath: number,
  isFirst: boolean,
  isLast: boolean,
  isReady: boolean,
  poiont: object,
  pointTitle: string,
  questions: Question[]
}

interface Question {
  answer1: string,
  answer2: string,
  answer3: string,
  id: string,
  question: string,
  rightAnswer: string
}

interface DatabaseObject {
  points: Point[]
  trailId: string
}

下面的代码是重定向到第二页

  const redirect = () => {
    history.push({
      pathname: '/user_app/quiz',
      state: databaseObject?.points[0].questions
    });
  }

second.tsx

interface Question {
    answer1: string,
    answer2: string,
    answer3: string,
    id: string,
    question: string,
    rightAnswer: string
  }

interface Props {
    questions: Question[]
  }


const QuizPage: React.FunctionComponent<Props> = (props) =>{
    const history = useHistory();
    const [answered, setAnswered] = useState(false);
    const [correct, setCorrect] = useState(false);
    const [clickedAnswer, setClickedAnswer] = useState('');
    const coreectAnswer = 'odpoved1'

    useEffect(() =>{
        console.log(props.questions)
        console.log(Object.values(props.questions))
        checkAnswer()
    })

您已将 location 对象传递给 history.push,因此组件可以在那里找到相应的 state

useEffect(() =>{
  console.log(props.location.state.questions)
  console.log(Object.values(props.location.state.questions))
  checkAnswer()
})

propsuseEffect 范围内不可用。 您必须将其作为 useEffect.

中的依赖项传递

尝试以下操作:

 useEffect(() =>{
        console.log(props.questions)
        console.log(Object.values(props.questions))
        checkAnswer()
    }, [props])