当null
在组件的构造函数之外初始化组件的状态时,状态never
在渲染函数中具有类型。
但是,在构造函数中初始化状态时,状态具有正确的类型。
根据 StackOverflow 上关于初始化状态的两种方式(在 babeled JS 中)的大多数问题,这两种方法应该是等效的。但是,在 Typescript 中,它们不是。这是错误还是预期的行为?
import * as React from "react";
import * as ReactDOM from "react-dom";
interface Person {
name: string;
address: string;
}
interface Props {
items: Person[];
}
interface State {
selected: Person | null;
}
class PersonSelector extends React.Component<Props, State> {
// DOES NOT WORK:
state = {
selected: null
};
constructor(props: Props) {
super(props);
// WORKS:
// this.state = {
// selected: null
// };
}
handleClick = (item: Person) => {
this.setState({
selected: item
});
};
render() {
const { selected } = this.state;
let selectedLabel = <div>None selected</div>;
if (selected) {
selectedLabel = <div>You selected {selected.name}</div>;
}
return (
<div>
{selectedLabel}
<hr />
{this.props.items.map(item => (
<div onClick={() => this.handleClick(item)}>{item.name}</div>
))}
</div>
);
}
}
const people: Person[] = [
{ name: "asdf", address: "asdf asdf" },
{ name: "asdf2", address: "asdf asdf2" }
];
document.write('<div id="root"></div>');
ReactDOM.render(
<PersonSelector items={people} />,
document.getElementById("root")
);
以下是 CodeSandbox 上的示例代码:https ://codesandbox.io/s/10l73o4o9q