反应访问状态

时间:2018-06-04 14:43:27

标签: javascript reactjs

您好,现在正努力学习React,仍然只是迈出了一步。 我在codepen中编写了代码(请参见底部的链接),在我的代码中我将几个日志放到控制台语句中,我无法弄清楚为什么我的函数handleSubmit位于最上面的组件中(&#39) ; TodoApp')无法访问状态?

我认为它无法访问它,因为我可以打印到上面的控制台文本'让current_todos = this.state.todos'但是我从未在控制台文本中看到过它。

如果这是不正确的,我应该如何访问状态呢? 注意:我意识到该函数中的许多代码都是冗余的,但我为了调试目的而声明了这些变量和日志语句

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = { 
      todos : [ ] 
    }
  }
  render() {
    return (
      <div className='todo-comp todo-app'>
        <h2>ToDo App</h2>
        <form onSubmit={this.handleSubmit}>
          <input type="text">
          </input>
        </form>
        <TodoList todos={this.state.todos}/>
       </div>
    )
  }
  handleSubmit(event) {
    let new_todo = event.target.children[0].value
    console.log("Submited: ".concat(new_todo))
    let current_todos = this.state.todos
    console.log("Succesfully accessed state")
    this.setState({"todos" : this.state.todos.push(new_todo)})
  }
}

class TodoList extends React.Component {
  constructor(props) {
    super(props)
  }
  render () {
    return (
      <ul className="todo-comp todo-list">
      {this.props.todos.map(
          function(item,key) {
            return(
              <li key={key} className="todo-comp todo-item">{item}</li>
            )
      })}
    </ul>
    )
  }
}

ReactDOM.render(
  <TodoApp />,
  document.getElementById('app'),
  console.log("App has been rendered"))

My CodePen Link

2 个答案:

答案 0 :(得分:1)

调用this.handleSubmit时,应该添加.bind(this),因为上下文在调用时是不同的。另一种选择是在构造函数中添加以下行:

this.handleSubmit = this.handleSubmit.bind(this)

答案 1 :(得分:1)

第一个错误是每次渲染都会重新创建handleSubmit

此代码将允许您查看输入值并提交等。希望这有帮助,如果您有任何问题,只需在下面发表评论。

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.onChange= this.onChange.bind(this)
    this.state = { 
      todos : [ ] 
    }
  }

  onChange(event) {
    this.setState({ text: e.target.value })
  }

  handleSubmit(event) {
    const { text } = this.state;
    // Your submit value;
    console.log(text)
  }
  render() {
    return (
      <div className='todo-comp todo-app'>
        <h2>ToDo App</h2>
        <form onSubmit={this.handleSubmit}>
          <input type="text" onChange={this.onChange}>
          </input>
        </form>
        <TodoList todos={this.state.todos}/>
       </div>
    )
  }
}
相关问题