gpt4 book ai didi

javascript - 使用状态和模板文字进行重定向 react

转载 作者:行者123 更新时间:2023-12-02 23:04:06 24 4
gpt4 key购买 nike

输入团队名称后,我想使用react以将我们重定向到指定页面(即:“teams/this.state.searchText”,其中搜索文本是用户在搜索表单中输入的内容)。我得到了一个不执行任何操作/不重定向的重新渲染...这可以通过 react 新的 v4 重定向组件来完成吗?

export default class Nav extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
searchText: ''
}
this.submit = this.submit.bind(this);
}
onSearchChange = e => {
console.log(e.target.value)
this.setState({ searchText: e.target.value });
}

submit = e => {
e.preventDefault();
// with the new search state from above, get the state and perform a search with it to local/team/"searchValue"

e.currentTarget.reset();
}
redirectIt = () => {
this.props.history.push(`teams/${this.state.searchText}`)
}
render() {
return (
<Navbar className="bg-light justify-content-between">
<Form onSubmit={this.submit} >
<FormControl type="text" placeholder="Search Team" className=" mr-sm-2" onChange={this.onSearchChange} />
<Button type="submit">Submit</Button>
</Form >
<div className='logo'>NHL</div>
<Form inline>
<Button type="submit" onClick={this.redirectIt}>Login</Button>
</Form>
</Navbar>
);
}

}

最佳答案

使用重定向,它看起来像这样。您基本上可以告诉浏览器转到不同的页面

import { Redirect } from 'react-router-dom'

export default class Nav extends React.Component {

constructor(props) {
super(props);
this.state = {
searchText: '',
isRedirected: false
}
}

onSearchChange = e => {
console.log(e.target.value)
this.setState({ searchText: e.target.value });
}

submit = e => {
e.preventDefault();
// with the new search state from above, get the state and perform a search with it to local/team/"searchValue"

e.currentTarget.reset();
}

redirectIt = () => {
this.setState({isRedirected: true})
}

render() {
// change the to prop to the next component
if (this.state.isRedirected) return <Redirect to=`/teams/${this.state.searchText}` />

return (
<Navbar className="bg-light justify-content-between">
<Form onSubmit={this.submit}>
<FormControl type="text" placeholder="Search Team" className=" mr-sm-2" onChange={this.onSearchChange} />
<Button type="submit">Submit</Button>
</Form >
<div className='logo'>NHL</div>
<Button onClick={this.redirectIt}>Login</Button>
</Navbar>
);
}

关于javascript - 使用状态和模板文字进行重定向 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664016/

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