reactjs - React - TypeError:无法读取未定义的属性“包含”
问题描述
我是 React 的新手,如果这太基础了,对不起。
我有一个输入表单,我正在尝试处理它的提交和更改,如下所示:
import { editMenuFormRules } from './forms/form-rules.js';
class Seeds extends Component{
constructor (props) {
super(props);
this.state = {
formData: {
coffee:''
},
menu:[],
editMenuFormRules:editMenuFormRules,
};
this.handleSubmitCoffees = this.handleSubmitCoffees.bind(this);
this.handleBeanFormChange = this.handleBeanFormChange.bind(this);
};
componentDidMount() {
if (this.props.isAuthenticated) {
this.getSeeds();
}
};
getSeeds(event) {
const {userId} = this.props
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds/${userId}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
this.setState({
menu: res.data.data[0].menu
})
})
.catch((error) => { console.log(error); });
};
为了处理提交和表单更改,我有:
handleSubmitCoffees(event) {
event.preventDefault();
const formType = this.props.formType
const {userId} = this.props
var headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
const data = {
coffee: this.state.formData.coffee
};
if (formType === 'EditMenu' && this.state.menu.includes(this.state.formData.coffee)) {
alert('This coffee already exists. Please add a new one.');
return (<Redirect to='/seeds' />);
};
const url = `${process.env.REACT_APP_WEB_SERVICE_URL}/edit_menu/${userId}`;
axios.post(url, data, headers)
.then((res) => {
this.clearForm()
console.log(data);
})
.catch((err) => {
if (formType === 'EditCoffee') {
this.props.createMessage('Coffee edit failed.', 'Please review your entry');
};
});
};
和:
handleBeanFormChange(event) {
console.log(event)
const obj = this.state.formData;
obj[event.target.name] = event.target.value;
this.setState(obj);
this.validateForm();;
};
最后,我的表格:
<form onSubmit={ (event) => this.handleSubmitCoffees(event) }>
<div className="field">
<input
name="coffee"
className="input is-large"
type="text"
placeholder="Enter Coffee Name"
value={this.state.formData.coffee}
onChange={this.handleBeanFormChange}
/>
</div>
</form>
但是,当我在表单中输入我的第一个项目时,我收到以下错误:
TypeError: Cannot read property 'includes' of undefined
指向这一行:
> 150 | if (formType === 'EditMenu' && this.state.menu.includes(this.state.formData.coffee)) {
this.state.formData.coffee
当我在表单中按 Enter 时,我没有定义吗?
我错过了什么?
解决方案
const obj = this.state.formData;
obj[event.target.name] = event.target.value;
this.setState(obj); // <-- this is setting 'target.name: value'
这实际上是覆盖formData
。我认为你的意思是:
const obj = Object.assign({}, this.state.formData);
obj[event.target.name] = event.target.value;
this.setState({ formData: obj });
请注意,克隆formData
对象很重要,因为您正在做的是改变状态,这是不希望的。
推荐阅读
- javascript - 从对象数组中搜索记录 - Javascript
- deep-learning - 与标准卷积相比,为什么在训练网络时瓶颈结构更慢且占用更多内存?
- javascript - 带有子域的 URL 正则表达式
- flutter-layout - 我想在一个也有 boxdecoration 的容器内有一排
- azure - 如何在 B2C 登录表单中显示 REST API 错误消息
- ios - 是否可以从其他应用程序使用 Podio iOS 应用程序?即打开 Podio 并在应用程序中显示特定条目
- swift - Swift:使用工具栏按钮删除 TableView 中的多个单元格
- ios - fcm onMessage 适用于模拟器,但不适用于物理设备
- javascript - 我似乎无法在 eventDrop 和 drop 上获取 resourceId,我正在使用 resourceTimelineMonth 并试图移动它们
- java - 方法后的 Jsoup 无法按预期方式工作