开发者问题收集

接收时 React props 未定义

2022-01-16
4196

我在传递 props 对象时遇到问题,第二页显示未定义。我尝试在第一页使用 console.log(databaseObject?.points[0].questions) 正确传递它,并且它是我想要的,但是当我尝试在第二页接收它时,它总是未定义。我在接收 props 时遗漏了什么吗?在第二页上,我从 console.log(props.questions) 得到了 'undefined',从 console.log(Object.values(props.questions)) 得到了 TypeError: "无法将未定义或空值转换为对象"

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()
    })
2个回答

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

useEffect(() =>{
  console.log(props.location.state.questions)
  console.log(Object.values(props.location.state.questions))
  checkAnswer()
})
morganney
2022-01-16

propsuseEffect 范围内不可用。 您必须将其作为依赖项传递到 useEffect

尝试以下操作:

useEffect(() =>{
        console.log(props.questions)
        console.log(Object.values(props.questions))
        checkAnswer()
    }, [props])
Shreekesh Murkar
2022-01-16