【问题标题】:Reactjs - modifying State and changing URL onChangeReactjs - 修改状态和更改 URL onChange
【发布时间】:2018-07-14 10:34:18
【问题描述】:

我正在尝试更改<Input type='select'> 上的stateURL onChange。 (我正在使用 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/`)
}

这是我得到的错误

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

console.log(this.props.history)undefined

我只需要在setState 发生后更改URL

【问题讨论】:

    标签: javascript reactjs url


    【解决方案1】:

    history 属性仅传递给分配给Route 组件的组件。

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

    如果您希望在不直接用于Route 的组件中使用route props,您可以使用withRouter

    由于setState 是异步的,您可以在对setState 的回调中推送到history,以确保在更改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)
    

    【讨论】:

    • 谢谢。这也确实解决了很多其他问题。我还希望 props.history.push 仅在 setState 发生之后发生。
    • 可以在this问题上应用相同的技术吗?
    • @SreekarMouli 我从未尝试过withRouter(NavLink);,但它可能会起作用,是的。
    • 我正在更新那个帖子,请看一下谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2021-07-02
    相关资源
    最近更新 更多