嗨,现在正在尝试学习 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"))
最佳答案
第一个错误是您的 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/