Reactjs,typescript无法在组件内设置初始状态

时间:2017-06-06 12:04:06

标签: reactjs typescript

我对React很新。我有一个渲染得很好的组件,当我尝试初始化状态时,它说它无法找到名称,因为我还没有声明它,所以如何正确初始化它?我正在使用:

  

"反应":" ^ 15.5.4",       " react-dom":" ^ 15.5.4",

下面一行中的组件错误:

export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (
        <section>
         <section>
             <h3>profile 1</h3>
             <div>baz</div>
         </section>
            <section>
                <h3>profile 2</h3>
                <div>shaz</div>
            </section>
        </section>
        )

}


 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)

修改

所以我设法通过每个人的帮助解决了这个问题:

interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}

3 个答案:

答案 0 :(得分:3)

this.state只是一个对象。在这种情况下,您可以在this.state对象上运行循环以获取每个名称的值,或者如果您希望可以在另一个父对象下设置所有名称,例如:假设您要在用户下存储名称键。那就是,

constructor(props){
  super(props);
  this.state = {
    users: [
      {name: 'baz'}, {name: 'shaz'}
    ]
  };
}

现在你应该循环this.state.users来获取名称值。

实施例,

// Loop using es6 map
componentWillMount() { 
  this.state.users.map( user => {
    console.log( user.name )
  } )
}

答案 1 :(得分:2)

正如人们所说,this.state必须是一个对象。

我认为真正的问题是初始化组件时。

export class Profile extends React.Component<{}, state>

你看到state?这是默认状态!由于你没有声明它,这是未定义的。请将其删除或将其设为void。或者,您可以在组件外部定义它:

1 - 第一个替代

export class Profile extends React.Component<{}, void> {
   constructor(props) {
    super(props)
    this.state = {
      users: [/* what you need */]
    }
  }
}

2 - 第二种选择

type state {
    {
      users: [/* what you need */]
    }
}

export class Profile extends React.Component<{}, state> {
   constructor(props) {
    super(props)
  }
}

答案 2 :(得分:1)

州是一个对象

像这样写它来定义状态数据:

this.state = {
   data: [
       {name: 'baz'}, 
       {name: 'shaz'}
   ]
}

然后按this.state.data访问状态值。

<强>更新

数据是一个数组,因此您需要使用map来打印所有值,如果要打印特定值,则使用该项的索引访问该值:

this.state.data[0].name   --->   baz

this.state.data[1].name   --->   shaz

使用map

this.state.data.map(el => {
   console.log('name', el.name);
})