[英]Setting the state with React + TypeScript
我無法弄清楚如何使用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>
);
}
}
在構造初始狀態時,您需要將props.items
傳遞給狀態:
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
this.state = {
stateItems: props.items
};
}
...
}
在構造函數中設置初始狀態時,只需將您想要的值this.state
:
constructor() {
// ...
this.state = { stateItems: ... /* initial value */ }
}
稍后在生命周期方法或事件偵聽器中,您可以使用setState
在構造函數中更改狀態
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.