Javascript ReactJS-将道具传递给子组件,但无法在子组件中访问它
我正在将道具时间从Home.jsparent组件传递到Game.js componentchild 但我无法在Game.js文件中访问它 Home.jsJavascript ReactJS-将道具传递给子组件,但无法在子组件中访问它,javascript,reactjs,Javascript,Reactjs,我正在将道具时间从Home.jsparent组件传递到Game.js componentchild 但我无法在Game.js文件中访问它 Home.js import React, {useState,Fragment} from 'react'; import {withRouter} from 'react-router-dom'; import Game from './Game'; const Home = ({history}) => { const [time, s
import React, {useState,Fragment} from 'react';
import {withRouter} from 'react-router-dom';
import Game from './Game';
const Home = ({history}) => {
const [time, setTime] = useState(0);
const [show, setShow] = useState(false);
const handleChange = (e) => {
setTime(e.target.value);
}
const handleClick = () => {
// console.log(time); // this console is working with time value.
setShow(!show);
history.push('/game');
}
return (
<Fragment>
<div className="col-md-6 offset-md-3">
<form>
<div className="form-group">
<label>Select the game time</label>
<select className="form-control" onChange={handleChange}>
<option>choose time</option>
<option value='5'>5 second</option>
<option value='10'>10 second</option>
<option value='15'>15 second</option>
<option value='20'>20 second</option>
<option value='25'>25 second</option>
<option value='30'>30 second</option>
</select>
</div>
<button to='/game' onClick={() => handleClick()} className="btn btn-dark btn-lg btn-block mt-5">Start</button>
</form>
</div>
{ show && <Game time={time} /> } // passing time props to Game component.
</Fragment>
)
}
export default withRouter(Home);
Game.js
import React from 'react';
const Game = ({time}) => {
useEffect(()=>{
console.log('Timer ',time); // unable to access time props coming from Home.js
//component i.e undefined
},[]);
return (
<div>
I am the Game.js component and i am unable to access 'time' props
</div>
)
}
export default Game;
为什么我无法访问“Home.js”文件中的“time”道具?
它应该是可访问的,并在useEffect中对其进行控制台时给出一个值。是否仅在第一次渲染或所有后续渲染中未定义时间?此外,您正在更改路由历史记录。请在设置显示状态后推送。那么,这是一条路线吗?然后你就不能得到你的时间状态了,因为你不再在家里渲染游戏组件了。谢谢@devserkan。它修复了我的问题。是否仅在第一次渲染或所有后续渲染上未定义时间?此外,您正在更改路由历史记录。设置“显示”状态后按。那么,这是一条路线吗?然后你就不能得到你的时间状态了,因为你不再在家里渲染游戏组件了。谢谢@devserkan。它解决了我的问题。