简体   繁体   中英

How to show a random string inside an array every 10 seconds React

it's working with console.log, it has to show on the front

render(){
 var myArray = [
    "Apples",
    "Bananas",
    "Pears"
  ];

  var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
  var intervalId = setInterval(() => {
    var timoutId = setTimeout(() => { 
        console.log(randomItem);
    }, 1000);
 }, 10000);
   return(
    <div>randomItem</div>
   )
 }

console.log shows a random string every ten seconds, but it doesn't work on the return()

  1. Move the set interval inside of component did mount (or else you will create intervals every time the component renders)
  2. Initialize state with an empty string
  3. setState inside the interval this will update state and cause the component to re-render
  4. use state inside the render function
  5. Clear interval in componentWillUnmount

 class SomeComponent extends React.Component{ state={ randomItem:'' } myArray = [ "Apples", "Bananas", "Pears" ]; randomItemGenerator = () => ( this.myArray[Math.floor(Math.random()*this.myArray.length)] ) componentDidMount(){ this.interval = setInterval(() => { this.setState({randomItem:this.randomItemGenerator()}) }, 1000) } componentWillUnmount(){ this.interval && clearInterval(this.interval) } render(){ return( <div>{this.state.randomItem} - {Math.floor(Math.random()*100)}</div> ) } } ReactDOM.render( <SomeComponent />, document.getElementById("react") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

  const [rndmItem, setRndmItem] = useState();

  const myArray = ["Apples", "Bananas", "Pears"];

  const timoutId = setTimeout(() => {
    var randomItem = myArray[Math.floor(Math.random() * myArray.length)];
    console.log(randomItem);
    setRndmItem(randomItem);
  }, 1000);
  return <div>{rndmItem}</div>;

Your react component render function should return just a representation of what your app looks like in a given state.

So you should not make any changes inside the render function.

If you use a class component you can handle how your app state changes through your class methods and the React built-in life-cycle methods. Here is an example:

 class App extends React.Component { state = { item: '' } interval = null myArray = ["Apples", "Bananas", "Pears"] randomItem = () => this.myArray[Math.floor(Math.random() * this.myArray.length)] componentDidMount() { this.interval = setInterval(() => { this.setState({item: this.randomItem()}); }, 10000); } componentWillUnmount() { clearInterval(this.interval) } render() { return <p>{this.state.item}</p> } } ReactDOM.render(<App />, document.getElementById('root'));
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

 class SomeComponent extends React.Component{ state={ randomItem:'' } myArray = [ "Apples", "Bananas", "Pears" ]; randomItemGenerator = () => ( this.myArray[Math.floor(Math.random()*this.myArray.length)] ) componentDidMount(){ this.interval = setInterval(() => { this.setState({randomItem:this.randomItemGenerator(i)}) }, 1000) } componentWillUnmount(){ this.interval && clearInterval(this.interval) } render(){ return( <div>{this.state.randomItem} - {Math.floor(Math.random()*100)}</div> ) } } ReactDOM.render( <SomeComponent />, document.getElementById("react") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>

What is it that you are getting? Also, use JSX when returning here. Try {randomItem}

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