Change to React State doesn't update display in functional component

后端 未结 1 943
花落未央
花落未央 2021-01-27 04:37

I created a simple, 2 component app where the name of the animal shows the icon of the animal to generalize an issue I am having in a more complicated app.

Once a random

相关标签:
1条回答
  • 2021-01-27 05:19

    You can wrap the animalIcon with attribute key , as you are passing props it seems its not updating correctly. This will tell react to update the icon if animal name is changed.

    <span key={props.animal}>{
          animalIcon
        }</span>
    

    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          currentAnimal: ''
        }
        this.getAnimal = this.getAnimal.bind(this);
      }
    
      getAnimal() {
    
        function getRandomAnimal(arr) {
          function getRandomIndex(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
          }
    
          return arr[getRandomIndex(0, arr.length - 1)];
        }
    
        const allAnimals = ['cat', 'dog', 'mouse'];
        const chosenAnimal = getRandomAnimal(allAnimals);
        this.setState({
          currentAnimal: chosenAnimal
        });
      }
    
      render() {
        return ( <
          Display getAnimal = {
            this.getAnimal
          }
          animal = {
            this.state.currentAnimal
          }
          />
        )
      }
    }
    
    function Display(props) {
      const icons = {
        cat: < i class = "fas fa-cat" > < /i>,
        dog: < i class = "fas fa-dog" > < /i>,
        mouse: < i class = "fas fa-mouse-pointer" > < /i>,
      }
    
      let animalIcon = icons[props.animal.toLowerCase()];
      console.log(props.animal);
    
      return ( <div ><h1> {
          props.animal
        }
        looks like <span key={props.animal}>{
          animalIcon
        }</span> < /h1> <
        button onClick = {
          props.getAnimal
        } > Get New Animal < /button> <
        /div>
      )
    }
    
    ReactDOM.render( < App / > , document.querySelector('.root'));
    <script src="https://use.fontawesome.com/releases/v5.5.0/js/all.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div class="root"></div>

    0 讨论(0)
提交回复
热议问题