【问题标题】:React : UI Data is not updated in ReactJSReact : UI 数据在 ReactJS 中没有更新
【发布时间】:2019-08-19 19:00:20
【问题描述】:

我正在研究 ReactJS 项目,我通过 API 显示数据。实际上,当我看到它显示 URL 过滤器数据时 REST 调用工作正常,但是当我刷新浏览器 UI 已更新时 UI 未更新。我是 ReactJS 的新手,有人可以帮我解决这个问题。

谢谢

代码

 class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

【问题讨论】:

  • 请附上Minimal, Complete, and Verifiable example,否则很难有人帮助您。
  • @Tholle,我刚刚更新了我的问题,请看一下,我是初学者,请帮助我
  • 没关系。请阅读我在上一条评论中发送给您的链接。尝试归结您必须使用尽可能少的代码但仍会产生相同问题的问题。
  • @Tholle,实际上我对大约 10-15 行的代码有疑问。我根据您的评论更新了问题

标签: javascript reactjs user-interface ecmascript-6


【解决方案1】:

您首先需要删除 componentWillUpdate,因为这已被声明为不安全。但是,您可以尝试 componentDidUpdate。这应该解决这个问题。您还可以使用 useEffect 挂钩,它基本上充当 componentDidMount 和 componentDidUpdate。

componentDidUpdate(prevProps) {
console.log(prevProps, this.props)
  // Typical usage (don't forget to compare props):
  if (this.props.parties !== prevProps.parties) {
    this.setState({
    data: props.parties,
    renderData:props.parties
  });
  }

}

【讨论】:

    【解决方案2】:

    我对这个问题有点困惑,但这可能是一个 setState 问题。除非您在 setState 之后进行回调,即在您编写的部分中,否则状态通常比渲染落后一步:

    this.setState({
        data: nextProps.parties,
        renderData:nextProps.parties
      });
    

    试试

    this.setState({
        data: nextProps.parties,
        renderData:nextProps.parties
      }, () => {});
    

    【讨论】:

    • 它不工作,你能帮我另一个解决方案吗?
    • 连湖人的回答都没有?我同意他使用新的 React 钩子“useEffect”的观点,你不必经历创建类组件的麻烦,只需使用带有 useState 和 useReducer 钩子的功能组件来创建你自己的状态管理。讨厌告诉你重写代码,但我认为从长远来看它会更容易和更干净。看看:reactjs.org/docs/hooks-intro.htm
    • 如果我几个月前就有 useEffect,我就不知道 componentDidUpdate 做了什么哈哈。
    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2018-08-31
    • 2021-06-22
    • 2017-09-05
    相关资源
    最近更新 更多