[英]The Data Flows Down in React.js
Hi Im just learning react I've small problem嗨我刚刚学习反应我有小问题
I want to learn how to pass state data to its Child as props我想学习如何将 state 数据作为道具传递给它的孩子
Here's me code这是我的代码
App.js应用程序.js
import React from "react";
import Clock from "./Clock";
import Test from "./Test";
import "./App.css";
function App() {
return (
<div className="App">
<Clock />,
<Test />
</div>
);
}
export default App;
Clock.js时钟.js
import React from "react";
import Test from "./Test";
class Clock extends React.Component {
state = {
date: new Date(),
};
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date(),
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<h3> Time Now</h3>
<Test date={this.state.date} />
</div>
);
}
}
export default Clock;
Here's the Child component I want to pass the state I named it test这是我想通过的子组件 state 我将其命名为 test
import React, { Component } from "react";
export class Test extends Component {
render() {
return (
<div>
<p>{this.props.date.toLocaleTimeString()}</p>
</div>
);
}
}
export default Test;
I got this error >>我收到了这个错误>>
TypeError: Cannot read property 'toLocaleTimeString' of undefined date undefined although I gave its parent props TypeError:无法读取未定义日期未定义的属性“toLocaleTimeString”,尽管我给了它的父道具
Please I need help
thanks in advanced
I guess you are seeing the error because of Test
Instance used in App.js
.我猜您看到错误是因为
App.js
中使用了Test
Instance 。 You are not passing in data over there.你没有在那里传递数据。 Removing it from there may get rid of error.
从那里删除它可能会消除错误。
App.js应用程序.js
import Clock from "./Clock";
import "./App.css";
function App() {
return (
<div className="App">
<Clock />
</div>
);
}
export default App;
You've passed props perfectly in Clock.js
however in App.js
you are not passing date
as a prop to <Test />
which is why you're getting the above error.您已经在
Clock.js
中完美地传递了道具,但是在App.js
中,您没有将date
作为道具传递给<Test />
,这就是您收到上述错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.