gpt4 book ai didi

javascript - React 未处理的拒绝(TypeError): Cannot read property 'state' of undefined

转载 作者:行者123 更新时间:2023-12-01 03:20:40 24 4
gpt4 key购买 nike

通过表单创建新游戏后,我可以重定向到新创建的游戏的显示页面,但如果我想转到游戏索引页面,它会再次重新加载新创建的游戏的显示页面。我需要刷新才能进入游戏的索引页面。

所以我创建了 clearSubmit() 方法,再次将 hasSubmit 值更改为 false,将该方法传递到显示页面的路由和显示页面的 component(GameShow .js) 我调用了clearSubmit()方法作为props。

现在,当我提交表单来创建游戏时,我收到此错误:

React Unhandled Rejection (TypeError): Cannot read property 'state' of 
undefined

src/components/GameShow.js:14

11 | constructor(props) {
12 | super(props)
13 | this.state = {
> 14 | game: this.props.location.state.selectedGame
15 | }
16 | }

App.js

 class App extends Component {

constructor(props) {
super(props)
this.state = {
games: [] ,
name: '',
img_url: '',
genre: '',
platforms: '',
video_url: '',
description: '',
hasSubmitted: false,
newGame: {}
}

this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
this.clearSubmit = this.clearSubmit.bind(this)
}


handleChange(e){
this.setState({
[e.target.name]: e.target.value
})
}


handleSubmit = (e) => {
e.preventDefault();
const { name, img_url, genre, platforms, video_url, description} =
this.state;


axios.post('http://localhost:4000/api/games', { name: name, img_url:
img_url, genre: genre, platforms: platforms, video_url: video_url,
description: description })
.then((result) => {
this.setState({
hasSubmitted: true,
newGame: result.data
})
});
}

clearSubmit() {
this.setState({
hasSubmitted: false
})
}

render() {
return (
<Router>
<div>
<main>
<Route exact path='/games' render={() => {
let newGame = this.state.newGame
return this.state.hasSubmitted
? <Redirect to=
{{pathname:`/games/${this.state.newGame.name}`,
state: {selectedGame: newGame}}}
/>
: <GameForm handleChange={this.handleChange}
handleSubmit={this.handleSubmit} games={this.state.games}
/>
} }
/>

<Route exact path='/games' render={() => {
return (
<GameIndex handleChange={this.handleChange}
handleSubmit={this.handleSubmit} games={this.state.games}
/>
)
} }
/>
<Route path="/games/:name" render={() => {
return (
<GameShow clearSubmit={this.clearSubmit} />
)
} }
/>
</main>
</div>

GameIndex.js

class GameIndex extends Component {


render() {
let videoGames = this.props.games.map((game, i) =>{
let pathname = `/games/${game.name}`

return (
<div key={i}>
<p><Link to=
{{ pathname, state: {selectedGame: game}}}> {game.name}</Link></p>
</div>
)
})

GameShow.js

 class GameShow extends Component {
componentDidMount() {
this.props.clearSubmit()
}

constructor(props) {
super(props)
this.state = {
game: this.props.location.state.selectedGame
}
}

我不知道我错过了什么。

谢谢。

最佳答案

我认为您没有将任何名为 location 的 Prop 对象传递到 GameShow.js 中(当您在 App.js 中渲染该对象时)。

关于javascript - React 未处理的拒绝(TypeError): Cannot read property 'state' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com