【发布时间】:2020-04-08 14:10:38
【问题描述】:
所以,我知道有很多关于这个的问题,我一直在寻找解决方案很长时间,但似乎没有任何工作,我几乎是 ReactJS 的初学者......
当我点击我的按钮时,URL 链接会发生变化,但页面还是一样的。我正在尝试构建一个具有某些级别的游戏(实际上是测验),因此组件始终相同但数据不同。
为了更好地解释:
App.js
import React from 'react';
import './App.css';
import {dataSet1, dataSet2} from './data/dataSet.js'
import Quiz from './Quiz.js'
import {BrowserRouter,Switch,Route, Link, withRouter} from 'react-router-dom';
import Button from '@material-ui/core/Button';
class App extends React.Component {
render() {
var style = {
width: "25%",
backgroundColor: "green",
float: "center",
padding: "12px 28px",
textAlign: "center",
color: "white",
}
return(
<div>
<BrowserRouter>
<Button style={style} component={Link} to="/level1">Play</Button>
<Switch>
<Route exact path="/level1" component={withRouter(Quiz)}>
<Quiz level={1} data={dataSet1}/>
</Route>
<Route path="/level2" component={withRouter(Quiz)}>
<Quiz level={2} data={dataSet2}/>
</Route>
</Switch>
</BrowserRouter>
</div>
)
}
}
export default App;
Quiz.js
import React from 'react';
import {Link, withRouter} from 'react-router-dom';
import Button from '@material-ui/core/Button';
class Quiz extends React.Component {
constructor(props) {
super(props)
this.state = {current:0, level: props.level, dataSet:props.data, correct:0, incorrect:0}
this.handleClick = this.handleClick.bind(this)
}
handleClick(choice) {
if (choice === this.state.dataSet[this.state.current].correct) {
this.setState({correct: this.state.correct + 1})
} else {
this.setState({incorrect: this.state.incorrect + 1})
}
if (this.state.current === 4) {
if(this.state.correct + this.state.incorrect === 4){
this.setState({current: this.state.current})
}
else {
this.setState({current: 0})
this.setState({incorrect: 0})
this.setState({correct: 0})
}
} else {
this.setState({current: this.state.current + 1})
}
}
render() {
var style = {
width: "25%",
display: "block",
backgroundColor: "green",
textAlign: "center",
color: "white"
}
if(this.state.current === 4 && this.state.correct === 5 ){
var l = this.state.level + 1
var next = '/level' + l
return(
<div>
<ScoreArea correct={this.state.correct} incorrect={this.state.incorrect} />
<h3 align="left">Passaste de nível!</h3>
<Button style={style} component={Link} to={next}>
Next Level
</Button>
</div>
)
}
else {
return(
<div>
<ScoreArea correct={this.state.correct} incorrect={this.state.incorrect} />
<QuizArea handleClick={this.handleClick} dataSet={this.state.dataSet[this.state.current]} />
</div>
)
}
}
}
....
export default withRouter(Quiz);
当我点击“下一级”时,我的 URL 变为 http://localhost:3000/level2,但页面没有改变。虽然,如果我刷新页面,它就可以正常工作,并且我的页面会按原样呈现。另外,如果我在第 2 级路由中单击“播放”,也会发生同样的情况:URL 更改为 http://localhost:3000/level1,但我的页面显示为第 2 级。
正在恢复:
如果不刷新页面,我无法从 level2 到 level1 或从 level1 到 level2。
如果有人可以帮助我,那就太好了。
【问题讨论】:
-
您的
Quiz.js对您提供的props有什么作用吗?不幸的是,您跳过了这部分代码... -
我更改了代码 rn。很抱歉!
-
谢谢,我会在一秒钟内发布答案
标签: javascript reactjs react-router react-router-dom