this.state 不会按预期更新

我正在尝试更新组件的状态。它按预期获取有关初始安装的一些数据componentDidMount()。我有一个componentDidUpdate()比较prevProps并且this.state会按预期“重新获取”。然而,在那些时刻之间,我不知道什么时候重新获取,因为prevProps和this.state变得相等,因为this.state没有更新(再次,因为 idk 在哪里放置新数据的获取)。


这是在 reactjs 应用程序的客户端。


constructor(props){

  super(props);

  this.state = ({ x:0 })

}


componentDidMount(){

  fetchingdata()

  this.setState({x:data[x]})

}


componentDidUpdate(prevState, prevProps, snapshot){

  if(prevProps.x !== this.state.x){

    return fetchingdata()

  }

}


render(){

  return(

    <div> this.state.x </div>

  )

}

如果您要console.log(this.state.x)进入componentDidUpdate(),即使服务器端已完全更新,它也会处于当前值。基本上是prevProps更新,this.state只有在加载时才会更新,因为componentDidMount()然后服务器更新并且不知道将数据发送到哪里。


阿波罗的战车
浏览 216回答 3
3回答

守着星空守着你

您似乎希望从远程服务器对组件中的某些数据进行最新更新。如果这是您想要实现的目标,您可以简单地每 x 秒使用setInterval(). 在你的componentDidMount()componentDidMount() {&nbsp; &nbsp; this.interval = setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; const data = this.fetchData() // Return result of an ajax call&nbsp; &nbsp; &nbsp; &nbsp; this.setState({myData: data})&nbsp; &nbsp; }, 1000) // Replace x with what suits you}还记得清除你的间隔 componentWillUnmount()componentWillUnmount() {&nbsp; &nbsp;clearInterval(this.interval);&nbsp;}

精慕HU

您的问题之一似乎在这里:render(){&nbsp; return(&nbsp; &nbsp; &nbsp;<div> this.state.x </div>&nbsp; )}在 React 中,为了访问某个状态,您必须在渲染区域中使用“{}”来输入 javascript。这实际上是关于 React 的一大优点。这允许您访问状态中的变量,甚至可以访问“render(){”和“return()”区域之间的任何 javascript。数据不返回的原因之一是没有访问 javascript 环境,因为它将“this.state.x”呈现为文本而不是状态。尝试render(){&nbsp; return(&nbsp; &nbsp;<div> {this.state.x} </div>&nbsp; )}

jeck猫

请使用promise进行API获取,请检查componentDidMountconstructor(props){&nbsp; super(props);&nbsp; this.state = ({ x:0 })}componentDidMount(){&nbsp; fetchingdata()&nbsp; &nbsp;.then((res) => {&nbsp; &nbsp; &nbsp; this.setState({x:res[x]})&nbsp;&nbsp; &nbsp;})}componentDidUpdate(prevState, prevProps, snapshot){&nbsp; if(prevProps.x !== this.state.x){&nbsp; &nbsp; return fetchingdata()&nbsp; }}render(){&nbsp; return(&nbsp; &nbsp; <div> this.state.x </div>&nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript