Reactjs - 修改状态并更改 URL onChange

Sre*_*uli 5 javascript url reactjs

我正在尝试更改上的stateURL 。(我正在使用反应带)onChange<Input type='select'>

import React, {Component} from 'react'
import {
    Input,
} from 'reactstrap'

export default class NewPostComponent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            selected: '',
        }
    }

    handleChange(event) {
        this.setState({
            selected: event.target.value,
        })
    }

    render() {
        return (
            <Input type='select' onChange={(e) => handleChange(e)}>
                <option>option 1</option>
                <option>option 2</option>
                <option>option 3</option>
                <option>option 4</option>
            </Input>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在更改,state但问题出在更改URL上。我已经尝试过props.history.push,但handleChange如下:

handleChange(event) {
    this.setState({
        selected: event.target.value,
    })
    this.props.history.push(`/${this.state.selected}/new/`)
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误

未捕获的类型错误:无法读取未定义的属性“push”

console.log(this.props.history)undefined

我只需要一种在发生后更改URL 的setState方法。

Tho*_*lle 6

prophistory仅传递给赋予Route组件的组件。

{/* The Login component will get the history prop */}
<Route path="/login" component={Login} />
Run Code Online (Sandbox Code Playgroud)

withRouter如果您希望组件中的路由属性Route不直接用于.

由于setState是异步的,您可以在history回调中推送 tosetState以确保在更改 url 之前状态已更改。

class NewPostComponent extends Component {
    state = {
        selected: ''
    }

    handleChange(event) {
        this.setState({
            selected: event.target.value,
        }, () => {
            this.props.history.push(`/${this.state.selected}/new/`)
        })
    }

    render() {
        return (
            <Input type='select' onChange={(e) => handleChange(e)}>
                <option>option 1</option>
                <option>option 2</option>
                <option>option 3</option>
                <option>option 4</option>
            </Input>
        )
    }
}

export default withRouter(NewPostComponent)
Run Code Online (Sandbox Code Playgroud)