如何在React Native中使用相同的状态调用获得不同的结果?

问题描述 投票:0回答:2

我为这个问题的混乱措辞道歉。基本上当我从这里呼叫状态时:

    this.state = {
     newdiscoverPlanet: [
      'sunp',
      'twop',
      'bluep',
      'purplep',
      'bluepurplep',
      'redp',
      'orangep'

    ],
};

_getRandomPlanet(){
  var planetItem = this.state.newdiscoverPlanet[Math.floor(Math.random()*this.state.newdiscoverPlanet.length)];
  this.setState({
    currentPlanet: planetItem,
  });
}

如何从同一个州获得不同的结果?

<Text>{this.state.currentPlanet}</Text>
<Text>{this.state.currentPlanet}</Text>
<Text>{this.state.currentPlanet}</Text>

我知道我可以添加两个更多不同的状态与newdiscoverPlanet的所有项目,但1)我有机会得到相同的结果2)这似乎太冗长的东西,可能有一个更容易的解决方案。

javascript reactjs react-native random jsx
2个回答
1
投票

不要将随机生成的名称放在状态中,而是调用函数在render函数中多次生成随机名称。

基本上这样的东西应该做的伎俩:

_getRandomPlanet(){
  var planetItem = this.state.newdiscoverPlanet[Math.floor(Math.random()*this.state.newdiscoverPlanet.length)];
  return planetItem
}

在你的JSX中:

<Text>{this._getRandomPlanet()}</Text>
<Text>{this._getRandomPlanet()}</Text>
<Text>{this._getRandomPlanet()}</Text>

0
投票

首先,如果newdiscoverPlanet是常量,它不应该处于状态(文件常量,静态成员,实例甚至支持成员都会这样做,但它实际上不是组件的状态)。

然后从我对你的问题的理解,似乎你想要随机选择newDiscoverPlanet而不是一个。

从我从评论中读到的内容,您似乎还需要为每个星球导入图像文件。

那么怎么样:

    import sunpImg from '../img/sunp.png';
    import twopImg from '../img/twop.png';
    import bluepImg from '../img/bluep.png';
    import purplepImg from '../img/purplep.png';
    import bluepurplepImg from '../img/bluepurplep.png';
    import redpImg from '../img/redp.png';
    import orangepImg from '../img/orangep.png';

    const planetsObj = [
        { name:'sunp', img: sunpImg },
        { name:'twop', img: twopImg },
        { name:'bluep', img: bluepImg },
        { name:'purplep', img: purplepImg },
        { name:'bluepurplep', img: bluepurplepImg },
        { name:'redp', img: redpImg },
        { name:'orangep', img: orangepImg },
    ];

    class YouComponent extends Component {

        state = {
            randomPlanets: this.getRandomPlanets()
        }
        getRandomPlanets() {
            // Note: since the randomization relies on random sorting
            // you won't have the same planet twice, if you want a 
            // subset (less planets) just use .slice(numOfItem)
            return [...planetsObj].sort(() => parseInt(Math.random() * 3, 10) - 1);
        }
        updateRandomPlanets() {
            this.setState(() => ({ randomPlanets: this.getRandomPlanets() }));
        }
        render() {
            const { randomPlanets } = this.state;
            // Note: if you randomize during render the renders
            // won't be consistent and the display won't be controllable
            return (
                {randomPlanets.map(planet => (
                    <div>
                        <img src={planet.img} />
                        <Text>{planet.name}</Text>
                    </div>
                ))}
            );
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.