gpt4 book ai didi

javascript - Reactjs - 修改状态和更改 URL onChange

转载 作者:行者123 更新时间:2023-11-29 20:52:12 28 4
gpt4 key购买 nike

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

这是我得到的错误

Uncaught TypeError: Cannot read property 'push' of undefined

console.log(this.props.history)undefined .

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

最佳答案

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

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

你可以使用 withRouter如果你想要 route props在不直接用于 Route 的组件中。

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

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)

关于javascript - Reactjs - 修改状态和更改 URL onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51337618/

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