ReactJS-每30秒从父组件到子组件传递对象不起作用

时间:2019-11-14 23:45:14

标签: javascript reactjs setinterval

我正在制作类似应用程序的游戏,其中每隔3秒从Game.js文件中将对象传递给子GameIntro.js文件,但看来我无法通过以下代码来实现。 我的意图是每3秒将不同的对象传递给子组件,并删除先前传递的组件。

Game.js文件::

import React from 'react';
import {gdatas} from './gamedata';
import GameIntro from './GameIntro';


const Game = () => {
    // const [item, setItem] = useState();
    return (
        <div>
            {gdatas && gdatas.map((gdata,i) => {
                return setInterval(() => (
                    <GameIntro key={i} gdata={gdata} />
                ),2000)
            }
            )}
        </div>
    )
}
export default Game;

GameIntro.js文件

import React from 'react';
// import {gdatas} from './gamedata';

const GameIntro = ({gdata}) => {

    const gameData = gdata.data.map((elm,i) => {
        return (
        <div className="col-md-6" key={i}>
            <div className="card">
                <img src={elm.image} className="card-img-top img-fluid" 
                    alt={elm.word} style={{'width' : '350px' , 'height' : '350px'}} />
                <div className="card-body">
                    <h5 className="card-title mt-3">{elm.word}</h5>
                </div>
            </div>
        </div>
        )
    })
    return (
        <div className="row">
            {gameData }
        </div>
    )
}
export default GameIntro;

2 个答案:

答案 0 :(得分:2)

setInterval返回一个id。将它作为.map的一部分返回是没有意义的。您可以使用setState并开始一次间隔(在这里我用setTimeout模拟间隔):

import React from 'react';
import {gdatas} from './gamedata';
import GameIntro from './GameIntro';


const Game = () => {
    const [item, setItem] = React.useState();

    React.useEffect(() => {
       let id;
       function next(i) {
         id = setTimeout(function() {
            if (i < gdatas.length) {
              setState(gdatas[i]);
              next(i+1);
            }
         }, 2000);
       }
       next(0);
       return () => clearTimeout(id);
    }, []); // only invoke on first render


    return (
        <div>
            {item && <GameIntro gdata={item} />}
        </div>
    )
}
export default Game;

答案 1 :(得分:1)

您无需在每个循环中为孩子提供每个项目,只需更新其上的 props 。一旦您了解了如何,这实际上是微不足道的:

以下示例:

import React, {useState, useEffect, useRef} from "react";

const GameObject = (props) => (
  <div className="bar">
    {props.current.name}
  </div>
)

function App() {
  const data = [{name: 'Luke'}, {name: 'Darth'}, {name: 'Yoda'}];
  let index = useRef(0);
  const [current, setCurrent] = useState(data[index.current]);

  useEffect(() => {
      function loop() {
        setInterval(() => {
          index.current = (index.current === data.length - 1) ? 0 : index.current + 1;
          setCurrent(data[index.current]);
        }, 1000);
      }

      loop();
  }, []);

  return (
    <div className="App">
      <GameObject current={current}/>
    </div>
  );
}