首页 > 解决方案 > 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 时,我没有定义吗?

我错过了什么?

标签: reactjs

解决方案


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对象很重要,因为您正在做的是改变状态,这是不希望的。


推荐阅读