React JS 如何将Quiz.js类组件的score变量传递给Graph.js函数组件
代码现存问题点
- 模板字符串语法错误:使用单引号包裹带
${score}的字符串,导致参数没有实际拼接,跳转后URL里是字面量的${score}文本,无法读取真实分数 - 硬跳转导致组件状态丢失:使用
window.location.href触发整页刷新,React应用的组件运行上下文完全重置,Graph组件拿不到Quiz组件传的props.score - 依赖项缺失:Graph组件的
useEffect为空依赖数组,就算拿到score值,组件更新后图表数据也不会同步刷新 - 导入遗漏:Graph组件使用了
<Link>组件但未从react-router-dom导入,会触发运行时报错 - 数据硬编码:图表里的错题数固定写为2,没有结合实际答题结果计算
可行实现方案
方案1:同页面组件传参(新手优先选择)
不需要路由跳转,直接在Quiz组件内部控制Graph组件的渲染,通过props直接传递score,逻辑最简单无额外依赖。
- 修改
Quiz.js:
import React, {Component} from 'react'; import PieChart from './Graph'; // 假设备题的QuestionBank已经全局引入 class Quiz extends Component{ constructor(props){ super(props) this.state={ userAnswer:null, currentIndex:0, options: [], quizEnd: false, score:0, disabled:true, showChart: false // 新增状态控制图表显示 } } // 重写checkStatistics方法 checkStatistics = () => { this.setState({ showChart: true }) } render() { // 触发查看统计后直接渲染Graph组件,传入score和错题数 if(this.state.showChart) { const wrongCount = QuestionBank.length - this.state.score return <PieChart correctCount={this.state.score} wrongCount={wrongCount} /> } // 保留原有quizEnd的渲染逻辑 const {currentIndex, quizEnd}= this.state if(quizEnd){ return( <div className="containerBox"> <h1> Game Over. Final score is {this.state.score} points</h1> <p> The correct answers for the quiz are</p> <ul> {QuestionBank.map((item,index) => ( <li className='options' key={index}> {item.answer} </li> ))} </ul> {currentIndex===QuestionBank.length-1 && <button className="attemptButton" onClick={this.attemptAnotherTry} disabled= {this.state.disabled}> Retest? </button> } {currentIndex===QuestionBank.length-1 && <button onClick={this.checkStatistics}>Check Statistics</button> } </div> ) } } } export default Quiz;
- 修改
Graph.js:
import React, {useState, useEffect} from 'react'; import { Pie } from 'react-chartjs-2'; import { Link } from 'react-router-dom'; const PieChart = (props) => { const [chartData,setChartData]= useState({}) // 从props取动态值 const correctCount = props.correctCount || 0 const wrongCount = props.wrongCount || 0 const chart = () =>{ setChartData({ labels: ['Correct Answers', 'Incorrect Answers'], datasets:[{ label: 'statistical chart', data:[correctCount, wrongCount], backgroundColor: ['rgba(255,99,132,1)','rgba(255,205,86,1)'], borderWidth: 4 }] }) } // 依赖项加上props值,保证数据变化时图表同步更新 useEffect(()=>{ chart() },[correctCount, wrongCount]) return( <div> <div style={{width:'1000px', height:'1000px',textAlign:"center",marginLeft:'250px'}}> <Pie data={chartData}/> <Link to="/Test" style={{textAlign:"center"}}>Attempt test again</Link> </div> </div> ) } export default PieChart;
方案2:路由跳转传参
如果需要独立的图表页面,就不要用整页硬跳转,使用React Router的导航能力携带参数跳转:
- 先给Quiz类组件包裹
withRouter高阶组件,拿到路由导航能力:
import { withRouter } from 'react-router-dom'; // 原有Quiz类的checkStatistics方法修改为 checkStatistics(score) { this.props.history.push({ pathname: '/Graph', search: `?score=${score}` }) } // 导出时包裹 export default withRouter(Quiz);
- 在Graph组件中从URL读取score参数:
import { useSearchParams } from 'react-router-dom'; const PieChart = () => { const [searchParams] = useSearchParams(); // URL参数默认是字符串,需要转成数字 const correctCount = Number(searchParams.get('score')) || 0 const wrongCount = QuestionBank.length - correctCount // 后续图表渲染逻辑和方案1完全一致 }
注:新手优先选择方案1,无需额外配置路由规则,不存在URL参数类型转换问题,是React体系内最稳定的跨组件传值方式。
内容的提问来源于stack exchange,提问作者Chaitali Tanawade
相关产品推荐
相关产品推荐

