gpt4 book ai didi

javascript - React Route With Params 找不到路线的位置

转载 作者:行者123 更新时间:2023-11-30 15:32:15 26 4
gpt4 key购买 nike

在为我遇到的问题找到解决方案后,我遇到了另一个问题。在我的路线上添加路线参数后, react 路由器不再识别它。

组件渲染新路由

import React, { Component } from 'react'
import { hashHistory } from 'react-router'

class Name extends Component {
constructor() {
super();
this.state = {username: ''};
this.onClickFunction = this.onClickFunction.bind(this)
}

onClickFunction(e) {
this.setState({username: e.target.value})
hashHistory.push({
pathname: '/level/' + this.state.username
})
}

render() {
return (
<div className="row">
<div className="col-md-12">
<div className="nameBox">
<form className="form-inline">
<input type="text" className="form-control" placeholder="Desiered Username" onChange={this.onUpdateUser} />
<button type="submit" className="btn btn-success" onClick={ this.onClickFunction }>Submit</button>
</form>
</div>
</div>
</div>
)
}
}

export default Name


import React from 'react'
import { Router, Route, hashHistory } from 'react-router'
import Home from './Home.js'
import Name from './Name.js'
import Level from './level.js'
import Level1 from './level1.js'
import Level2 from './level2.js'
//import result from './result.js'

const routes = (
<Router history={hashHistory}>
<Route path='/' component={Home} >
<Route path='/name' component={Name} />
<Route path="/level/:username" component={Level} />
<Route path='/level1' component={Level1} />
<Route path='/level2' component={Level2} />
</Route>
</Router>
);

export default routes;

我是 React 的新手,这是我的第一个帮助学习它的应用程序。我已经四处搜索,虽然很普遍,但这个问题似乎模棱两可。任何帮助将不胜感激!谢谢!

最佳答案

利用 this.context.router.push() 发送动态路由以及 event e 不引用输入而是引用按钮e.target.value 不会给出输入的值。您应该实现 onUpdateUser 函数以使用输入值更新状态

import React, { Component } from 'react'
import { hashHistory } from 'react-router'

class Name extends Component {
constructor() {
super();
this.state = {username: ''};
this.onClickFunction = this.onClickFunction.bind(this);
this.onUpdateUser = this.onUpdateUser.bind(this);
}
static contextTypes = {
router: React.PropTypes.object
}

onClickFunction() {
this.context.router.push({
pathname: '/level/' + this.state.username
})
}
onUpdateUser(e) {
this.setState({username: e.target.value});
}
render() {
return (
<div className="row">
<div className="col-md-12">
<div className="nameBox">
<form className="form-inline">
<input type="text" className="form-control" placeholder="Desiered Username" onChange={this.onUpdateUser.bind(this)} />
<button type="button" className="btn btn-success" onClick={ this.onClickFunction.bind(this) }>Submit</button>
</form>
</div>
</div>
</div>
)
}
}

export default Name

关于javascript - React Route With Params 找不到路线的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42059826/

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