简体   繁体   中英

React/JSX: Can I use a state variable in another state variable?

I have something like this, where I would like to create array in the state from a variable initialized directly above it. I get the error cards is not defined . Is there a way around this? I need to set this array specifically in the state.

class Example extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      cards: [
        {
          name: "Name 1",
          description: "dfdsfaf",
        },
        {
          name: "Name 2",
          description: "dsfsfasf",
        },
        {
          name: "Name 3",
          description: "daslkdjadlajsd",
        },
     ],
      names: cards.map(item => item.name)
    };
   }
...
}

You can do this in javascript as follows:

const cards = [...]
const names = = cards.map(...)
this.state = { cards: cards, names: names }

You should probably not do this though and set state to only the cards and move the call to calculate the names to your render method

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