【问题标题】:Setting the state with React + TypeScript使用 React + TypeScript 设置状态
【发布时间】:2017-05-15 23:16:01
【问题描述】:

我不知道如何使用 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>
        );
    }
}

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    在构造初始状态时需要将props.items传递给状态:

    export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
        constructor(props: ITodoListProps) {
            super(props);
    
            this.state = {
                stateItems: props.items
            };
        }
        ...
    }
    

    【讨论】:

    • 有没有办法做到这一点,而不必总是写super(props) 和props:ITodoListProps?它只是样板文件,不应该是必需的,但如果我在构造函数之外分配状态,它似乎失去了类型安全......
    • @binki 你必须调用super,这是一个javascript的东西:“如果子类中存在构造函数,它需要在使用“this”之前先调用super()”(developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… )。至于props,如果你想让编译器知道你需要指定它们的类型。
    【解决方案2】:

    在构造函数中设置initial状态时,只需将你想要的值赋值给this.state:

    constructor() {
      // ...
      this.state = { stateItems: ... /* initial value */ }
    }
    

    稍后在生命周期方法或事件侦听器中,您可以使用 setState 在构造函数中更改状态

    【讨论】:

    • 我认为这可以通过显示对 super 的调用和传递道具来改善。人们可能会认为你在暗示没有必要。
    猜你喜欢
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2018-12-20
    相关资源
    最近更新 更多