Reactjs - 在onChange事件中修改状态和URL

5

我正在尝试在一个<Input type='select'>上通过onChange来改变stateURL。(我正在使用reactstrap)

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

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

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

我遇到了以下错误:

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

console.log(this.props.history)返回值为undefined

我需要在setState发生后更改URL,请问有什么方法吗?

1个回答

6

只有被赋予给 Route 组件的组件才会传递 history 属性。

{/* The Login component will get the history prop */}
<Route path="/login" component={Login} />

您可以使用withRouter来在非直接用于Route的组件中使用路由属性
由于setState是异步的,因此您可以在回调函数中将状态更改推送到history,以确保在更改URL之前状态已更改。请注意保留HTML标记。
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)

谢谢你。这真的解决了很多其他问题。我还希望props.history.push发生在setState之后。 - Sreekar Mouli
可以将相同的技术应用于这个问题吗? - Sreekar Mouli
@SreekarMouli 我从未尝试过 withRouter(NavLink); 但它可能有效。 - Tholle
我正在更新那篇文章,请查看并感谢。 - Sreekar Mouli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接