将JSX附加到ReactJS中的状态变量 [英] Appending JSX to a state variable in ReactJS

查看:53
本文介绍了将JSX附加到ReactJS中的状态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个状态变量,该变量存储将在 render()方法中呈现给DOM的JSX代码.这是状态结构以及我当前拥有的状态变量 jsxComp

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
}

我想做的是,我试图将JSX代码(div)追加到如下所示的for循环内的该变量中,

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.

推荐答案

从不将实际元素存储在 state 中.State应该只包含要渲染的纯数据,而不是实际的标记.而是根据状态使您的 render()方法有条件地呈现:

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>
    );
  }
}

每当 state 更改时,都会调用

您的 render()方法.然后,React将比较渲染结果并在元素更改的地方更新DOM.

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.

您也不应循环调用 setState().首先收集更改,然后使用整个更改后的数组调用 setState .要将附加实际上添加到处于状态的现有数组中,您可以执行以下操作:

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]});

这篇关于将JSX附加到ReactJS中的状态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆