簡體   English   中英

使用React + TypeScript設置狀態

[英]Setting the state with React + TypeScript

我無法弄清楚如何使用TypeScript設置我的React組件的狀態。

  • 我正在做一個簡單的Todo列表
  • 我有一個整個列表的組件: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM