使用状态和模板文字进行重定向反应

时间:2019-08-26 19:42:03

标签: javascript html node.js reactjs

输入团队名称后,我想做出反应以将我们重定向到指定页面(即:“ teams / this.state.searchText”,其中包含用户在搜索表单中输入的搜索文本)。我得到了一个不执行任何操作/不进行任何重定向的重新渲染...可以通过对新的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>
    );
}

}

1 个答案:

答案 0 :(得分:1)

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

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>
    );
}