由于它是一个无状态组件,它没有组件生命周期。因此你不能指定一个constructor
.
您必须扩展React.Component
以创建一个有状态组件,然后该组件将需要一个构造函数,并且您将能够使用state
.
更新
自从React 16.8.0和 Hooks 被引入以来,有更多的选择。
Hooks 是一个新的特性提案,它可以让你在不编写类的情况下使用状态和其他 React > 特性。它们作为 > v16.8.0 的一部分在 React 中发布
无国籍:
import React from "react"
const Stateless = ({name}) => (
<div>{`Hi ${name}`}</div>
);
有状态:
可以访问组件生命周期方法和本地状态。
class Stateful extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
componentDidUpdate() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
render() {
const { count } = this.state;
return (
<div>
<p>You've clicked {count} times.</p>
<button onClick={() => this.setState({ count: count + 1 })}>
Click me
</button>
</div>
);
}
}
使用钩子:
能够使用State Hook
和Effect Hook
。
如果您熟悉 React 类的生命周期方法,您可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。
import React, { useState, useEffect } from "react";
const UsingHooks = () => {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You've clicked ${count} times.`;
});
return (
// <> is a short syntax for <React.Fragment> and can be used instead of a wrapping div
<>
<p>You've clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}