简体   繁体   中英

Appending JSX to a state variable in ReactJS

I have a state variable which stores JSX code that will be rendered to the DOM in the render() method. Here is the structure of state and the state variable jsxComp that I currently have,

state = {
    isLoggedin: false,
    jsxComp: null
}

What I am trying to do is I am trying to append JSX code ( a div ) into this variable inside a for loop as follows,

for(let i=0; i<postCount; i++){
    this.setState({
        //Append a div to the jsxComp variable
     })
}

How can I do that? + operator does not seem to work in this case.

Never store actual elements in state . State should only contain the pure data to render, not the actual markup. Instead make your render() method conditionally render based on the state:

class MyComp extends React.Component {
  state = {
    isLoggedIn: false,
  };

  render() {
    const {isLoggedIn} = this.state;

    return (
      <div>
        {/* conditionally render based on isLoggedIn */}
        <p>{isLoggedIn ? 'You are logged in' : 'Please log in.'}</p>
        <button onClick={() => this.setState({isLoggedIn: true})}>
          Log In
        </button>
      </div>
    );
  }
}

Your render() method will be called whenever the state changes. React will then diff the result of the render and update the DOM where elements changed.

You also should not call setState() in a loop. First collect the changes and then call setState with the whole changed array. To actually append something to an existing array in state you would do:

this.setState(state => {jsxComp : [...state.jsxComp, newElement]});

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