简体   繁体   中英

Javascript instance variable didn't get rendered in React class component when calling setState

A react class component is mounted to html root node. It has two react element h1 tag in its body. One h1 element is directly render inside the render method. Another h1 is decleared in React component class and passed into Render function as a variable.

import React, { Component } from "react";

export default class Test extends Component {
  state = {
    count: 0,
  };

  current_count = (<h1>current count is {this.state.count}</h1>);

  render() {
    return (
      <>
        {this.current_count}
        <h1>current count is {this.state.count}</h1>
        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          click me
        </button>
      </>
    );
  }
}

When I clicked the button, it should increase the count , only the react element h1 inside the render function will updated with it's state content.

The following photo is shown the second h1 tag showing count is 4 when I clicked the button 4 times.

在此处输入图像描述

Your current_count is a property that gets created in the constructor, before mount, and only then. Your current code is like

export default class Test extends Component {
  constructor() {
    this.state = {
      count: 0,
    };
    this.current_count = (<h1>current count is {this.state.count}</h1>);
  }

And the constructor only runs once.

You'll need some other method to update it. The best way would be to only generate the JSX on render - perhaps have a function instead that returns the <h1> .

 class Test extends React.Component { state = { count: 0, }; getCurrentCount() { return ( <h1>current count is {this.state.count}</h1> ); } render() { return ( <React.Fragment> {this.getCurrentCount()} <h1>current count is {this.state.count}</h1> <button onClick={() => { this.setState({ count: this.state.count + 1 }); }} > click me </button> </React.Fragment> ); } } ReactDOM.createRoot(document.querySelector('.react')).render(<Test />);
 <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div class='react'></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM