我的 App 组件中有以下路由:
<Route path ='/:id' component = {VideoPage} />
当访问此路由时,我希望 VideoPage 组件使用 :id 参数向 API 发出 axios 请求,然后我想更新 VideoPage 的状态并渲染出 API 返回的信息。
这是我目前在 VideoPage 组件中所做的,它不起作用:
export default class VideoPage extends Component {
constructor(props){
super()
this.state = {
id: props.match.params.id,
mainVideo: defaultVideo
};
}
componentDidUpdate(){
axios.get(getVideo(this.state.id))
.then(res => {
console.log(res)
this.setState({
mainVideo: res.data
})
})
.catch(err => console.log(err))
}
render() {
// render several components, passing them pieces of state from this component
}
问题是当我从 componentDidUpdate 中调用 this.setState
时,我得到了一个无限循环。
那么您将如何着手执行此操作(使用来自 ReactRouter 和 的参数进行 API 调用)?
最佳答案
你必须在componentDidUpdate中检查你想要跟踪的状态的变化,否则,当你在componentDidUpdate中调用setState时,它会触发更新并导致无限循环。
我假设您想在每次更改 id 状态时调用 API。可以使用componentDidUpdate的prevState参数,引用这个link
你可以像这样比较prevState和当前状态来检查状态
componentDidUpdate(prevProps, prevState) {
if (this.state.id !== prevState.id) {
axios.get(getVideo(this.state.id))
.then(res => {
console.log(res)
this.setState({
mainVideo: res.data
})
})
.catch(err => console.log(err))
}
}
但 componentDidUpdate 是在更改发生后调用的,因此它不会在初始渲染中被调用,因此您必须将 API 调用也放在 componentDidMount 中。
componentDidMount() {
this.fetchVideo()
}
componentDidUpdate(prevProps, prevState) {
if (this.state.id !== prevState.id) {
this.fetchVideo()
}
}
fetchVideo() {
axios.get(getVideo(this.state.id))
.then(res => {
console.log(res)
this.setState({
mainVideo: res.data
})
})
.catch(err => console.log(err))
}
关于javascript - 如何使用来自 React Router 的路由参数发出 axios 请求,然后根据响应更新状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65367132/