我无法弄清楚如何使用TypeScript设置我的React组件的状态。
TodoList
TodoList
组件的道具,然后立即将其设置为状态,以便我可以使用import * as React from "react";
import { TodoItem, ITodoItem } from "../TodoItem";
interface ITodoListProps {
items: ITodoItem[];
}
interface ITodoListState {
stateItems: ITodoItem[];
}
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
// Trouble figuring this part out
// I'd like to set the state to the list from the
// props, as a seed.
this.setState({
stateItems: this.state.stateItems
});
}
public render() {
return (
<div>
<ul>
// This should probably be displaying the items from the state, and not the props.
{this.props.items.map((todo, i) => {
return <TodoItem key={i} name={todo.name} />
})}
</ul>
</div>
);
}
}
答案 0 :(得分:4)
构建初始状态时需要将props.items
传递给状态:
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
this.state = {
stateItems: props.items
};
}
...
}
答案 1 :(得分:3)
在构造函数中设置初始状态时,只需将您想要的值指定为this.state
:
constructor() {
// ...
this.state = { stateItems: ... /* initial value */ }
}
稍后在生命周期方法或事件侦听器中,您可以使用setState