因此,我正在尝试与 rails 一起学习 react(将 rails 纯粹用作 API)。我正在制作一个简单的待办事项应用程序,并在尝试“创建”列表时卡住了。
我在这里显示了一个“新列表”组件,主要取自反应表单教程:
import React, { Component } from 'react';
import axios from 'axios';
class ListForm extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
description: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value});
}
handleSubmit(e) {
console.log("Form submitted with: " + this.state.value)
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Title:
<input name="title" type="text" value={this.state.value} onChange={this.handleInputChange} />
</label>
<label>
Description:
<textarea name="description" value={this.state.value} onChange={this.handleInputChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default ListForm;
我在这里显示了我的 ListContainer
import React, { Component } from 'react';
import axios from 'axios';
import List from './List';
import ListForm from './ListForm'
class ListContainer extends Component {
constructor(props){
super(props)
this.state = {
lists: []
}
this.addNewList = this.addNewList.bind(this)
}
componentDidMount() {
axios.get('/api/v1/lists.json')
.then(response => {
console.log(response)
this.setState({
lists: response.data
})
})
.catch(error => console.log(error))
}
addNewList(title, description) {
axios.post('/api/v1/lists.json', {
title: title,
description: description
})
.then(function (response) {
console.log(response);
const lists = [ ...this.state.lists, response.data ]
console.log(...this.state.lists)
this.setState({lists})
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div className="lists-container">
{this.state.lists.map( list => {
return (<List list={list} key={list.id} />)
})}
<ListForm onSubmit={this.addNewList} />
</div>
)
}
}
export default ListContainer;
我的问题来自对提交回调的误解。我知道当我在表单上执行“onSubmit”时,它使用 addNewList 函数作为回调......但我真的不明白 ListForm 中状态的连接是如何进入该回调函数的。我显然做错了什么,因为它不起作用,并且当前控制台显示“提交的表单:未定义”,所以它根本没有正确传递参数。
我对 React 还是很陌生,并且对 JS 非常生疏(自从我使用它以来已经有一段时间了,所以我确定这里有一些新手错误)。此外 axios 基本上是一个“更好”的获取 fwiw。
我也不会撒谎,例如,我不完全理解我们为什么这样做this.handleSubmit = this.handleSubmit.bind(this);(以及其他类似的)