Update React page in class-based component without using useState.
P粉739886290
P粉739886290 2023-08-03 21:16:09
0
1
662
<p>I'm using React's class-based component to display all the tokens first. Then I want to display two texts with spanid at the same time, regardless of the order, using the previous and next buttons to re-render the page. There will be n*(n-1) possibilities for re-rendering the page. This is because the first text with a spanid will be paired with the second text with another spanid, up to the n-1th token with a spanid. For n pieces of text with spanid, the page can be re-rendered n*(n-1) times using the previous/next buttons. Since I'm writing code using React's class-based components, I'm not sure how to handle this using useState and props like I would in a functional setup. Any help on this issue is greatly appreciated. </p> <pre class="brush:php;toolbar:false;">import React from 'react'; import './App.css'; const record = [ { "tid": 1, "token_text": "Canis Familiaris", "spanid": 1, "label": "Name" }, { "tid": 2, "token_text": "is" }, { "tid": 3, "token_text": "the" }, { "tid": 4, "token_text": "scientific name", "spanid": 2, "label": "name type" }, { "tid": 5, "token_text": "of" }, { "tid": 6, "token_text": "dog", "spanid": 3, "label": "species" }, { "tid": 7, "token_text": "." } ]; class Relation extends React.Component { const input_tokens = record; var cntr = 200; input_tokens.forEach(tk => { const span = tk['spanid']; if (!tk['spanid']) { tokens_to_render.push( <div key= {`id${cntr}`} > <div id = {`label${cntr}`} className='no-label' key={tk.tid}>--</div> <div key={cntr} id = {`span${cntr}`} index={tk['spanid']} > {tk['token_text']} </div> </div> ); } else { tokens_to_render.push( <div key = {`id${cntr}`} > <div id = {`label${cntr}`} className='label' key={tk.tid} >{tk['label']}</div> <div key={cntr} id = {`span${cntr}`} index={tk['spanid']} > {tk['token_text']} </div> </div> ); }; cntr = cntr 1; }); return ( <div key="outer" > <div key="id" className="control-box"> {tokens_to_render} </div> </div> ) } } export default Relation;</pre> <p><br /></p>
P粉739886290
P粉739886290

reply all(1)
P粉413307845

Translation: Hooks like useState can only be used in function components. To use state in a class component:

  • Return the JSX to be displayed from the render() method.
  • Assign the initial state to the state attribute.
  • Call this.setState to update the status.

For example:


class Example extends React.Component {
    state = {
        count: 0
    }
    
    render() {
        return <div>
            <button onClick={() => this.setState({count: this.state.count + 1})}>
                Increment count
            </button>
            <p>Clicked {this.state.count} times</p>
        </div>;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template