javascript - react 访问状态

标签 javascript reactjs

嗨,现在正在尝试学习 React,但仍只是起步阶段。 我在 codepen 中编写了下面的代码(请参阅底部的链接),在我的代码中我将一些日志放入控制台语句我无法弄清楚为什么我的函数 handleSubmit最上面的组件('TodoApp')中的哪个无法访问状态?

我认为它无法访问它,因为我可以打印到“let 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

最佳答案

第一个错误是您的 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>
    )
  }
}

关于javascript - react 访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50683171/

相关文章:

javascript - 如何应用这个AJAX请求而不需要重新加载页面才能生效?

javascript - 悬停幻灯片重新定位错误在 IE 中不起作用

javascript - 自动滚动以搜索输入字段并且不在移动设备上显示旧的搜索选项

javascript - 如何确保这些圆圈始终接触 - 包装问题

reactjs - 我应该对功能组件使用 _myMethod 吗?

css - 设计 SAAS 我想要 Box 布局但无法得到它

reactjs - React Material UI 表排序

Javascript点对点 Angular 计算

javascript - 如何更改 li 标签内的特定组件(react js);

javascript - 允许用户仅访问他/她的仪表板