因为它是一个无状态组件,所以它没有组件生命周期。因此您无法指定constructor
。
您需要扩展React.Component
来创建一个有状态组件,然后需要一个构造函数,您将能够使用state
。
更新
自React 16.8.0和引入钩子之后,有更多的选择。
钩子是一项新的功能提议,它允许您在不编写类的情况下使用状态和其他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>
);
}
}
使用Hooks:
能够使用State Hook
和Effect Hook
。
如果您熟悉React类生命周期方法,可以将useEffect Hook视为componentDidMount、componentDidUpdate和componentWillUnmount的组合。
import React, { useState, useEffect } from "react";
const UsingHooks = () => {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You've clicked ${count} times.`;
});
return (
<>
<p>You've clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
React.Component
进行扩展。 - Ematipico