【问题标题】:How to render updated state in react Js?如何在 React Js 中呈现更新状态?
【发布时间】:2021-11-10 14:04:03
【问题描述】:

我正在类组件中处理 React Js 我正在声明一些状态,然后从 API 获取数据并将该状态更改为新值,但 React 并未呈现该新状态值。但是如果我在 console.log() 中声明它会在控制台上给我新的价值。

我的代码

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      unread: 0,
    }
    this.getUnread()
  }
  getUnread = async () => {
    let data = await Chatapi.get(`count/${this.props.auth.user.id}/`).then(({ data }) => data);
    this.setState({ unread: data.count });
    console.log(this.state.unread)
  }
  render() {
    const { auth } = this.props;
    return (
      <div>
        {this.state.unread}
      </div>
    )
  }

这是在控制台上打印 2 但在屏幕上呈现 0。如何获取更新后的状态 (2) 以在屏幕上呈现。

如果我访问另一个页面然后返回此页面,那么它正在呈现新的状态值 (2)。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    请在componentDidMount中调用getUnread()函数,类似这样

    componentDidMount() {
      this.getUnread()
    }
    

    【讨论】:

    • 仍然和上面一样工作
    • 你能像这样更新状态吗:this.setState((state, props) => { return {unread:data.count}; });也请在渲染方法上使用 console.log
    【解决方案2】:

    这是因为在 React 类组件中,在调用 setState 时,不直接传递值来设置状态(并因此重新渲染组件)会更安全。这是因为状态被设置为命令时会发生什么,但是当组件重新渲染时,状态再次设置回初始值,这就是被渲染的内容

    您可以阅读react docs 中给出的此问题及其解决方案

    您传递一个设置值的函数。

    所以,setState 的代码是

     this.setState((state) => { unread: data.count });
    
    

    因此,您更新的代码将是:

    class Home extends Component {
      constructor(props) {
        super(props);
        this.state = {
          unread: 0,
        }
        this.getUnread()
      }
      getUnread = async () => {
        let data = await Chatapi.get(`count/${this.props.auth.user.id}/`).then(({ data }) => data);
        this.setState((state) => { unread: data.count });
        console.log(this.state.unread)
      }
      render() {
        const { auth } = this.props;
        return (
          <div>
            {this.state.unread}
          </div>
        )
      }
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2021-12-21
      • 1970-01-01
      • 2020-06-21
      • 2018-08-27
      • 1970-01-01
      • 2019-04-10
      • 2021-07-30
      • 2017-09-21
      相关资源
      最近更新 更多