我正在学习React并按照他们的分步教程进行操作,但是没有使用JSX。我对本教程不太了解,但遇到了麻烦。没有调用componentDidMount方法,因此我的计时器没有更新。
任何帮助将不胜感激。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Test</title>
<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>
<!--<script crossorigin src="assets/react.development.16.4.1.js"></script>-->
<!--<script crossorigin src="assets/react-dom.development.16.4.1.js"></script>-->
</head>
<body>
<div id="root"></div>
<script>
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello World!",
date: new Date(),
}
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
let fragment = React.createElement(React.Fragment, null, [
React.createElement("h1", {key: "message"}, this.state.message),
React.createElement("p", {key: "time"}, this.state.date.toLocaleTimeString())
]);
return fragment;
}
tick() {
this.setState({
date: new Date()
});
}
}
ReactDOM.render(new App().render(), document.getElementById("root"));
</script>
</body>
</html>
答案 0 :(得分:2)
我认为问题出在一个地方
ReactDOM.render(new App().render(), document.getElementById("root"));
为什么这行不通?
因为渲染将返回App组件的孩子而不是App本身 。您的孩子将首先被挂载,并且永远不会渲染您的应用 ,因此没有App组件的componentDidMount
上下文不正确。在这里尝试使用错误功能
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Hello World!",
date: new Date(),
}
}
componentDidMount() {
console.log("mounting")
this.timerID = setInterval(
() => {
this.tick()
},
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
let fragment = React.createElement(React.Fragment, null, [
React.createElement("h1", {key: "message"}, this.state.message),
React.createElement("p", {key: "time"}, this.state.date.toLocaleTimeString())
]);
return fragment;
}
tick = () => {
debugger
this.setState({
date: new Date()
});
}
}
ReactDOM.render(React.createElement(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>
<!--<script crossorigin src="assets/react.development.16.4.1.js"></script>-->
<!--<script crossorigin src="assets/react-dom.development.16.4.1.js"></script>-->
<div id="root"></div>