jeudi 2 janvier 2020

How to save random ui state in react-redux properly

I have a React Redux web app
In List of items I want to generate a random color for each item, at the first time
and then keep it with the same color.

My problem is to decide where to do the random action:

  • If I do it in the component class
    It will cause render multiple times, and will cause an error
  • I can do it in the action that fetches the list data, but it will
    make the action to know about the colors(array) in the ui.

React List sample

function render() {
    const { contacts } = this.props;
    const contacts = mailContacts.map(({
      id,name, snippet, colorIndex
    }) => {
      const index;
      if(colorIndex == undefined) {
        index = myRandom(colorsCount);
        // This is bad solution it rerendes ui 
        // Too much times and causes error
        this.props.saveRandomColor(id, colorIndex);
      } else {
        index = colorIndex;
      }
      contacts.map(contact => {
        return (
          <Contact
            className="contact"
            key={name}
            snippet={snippet}
            colorIndex={index}
          />
        );
      })
    });
  }



Aucun commentaire:

Enregistrer un commentaire