React-TypeError:无法读取未定义的属性“ includes”

时间:2019-10-11 20:57:21

标签: reactjs

我是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)) {

我在窗体上按Enter键时没有定义this.state.formData.coffee吗?

我想念什么?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

问题出在这里,那里有一个GET请求“ menu”值:

componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getSeeds(); ///// <------------
    }
  };

后端有一个格式错误的json响应对象:

response_object = {
              'status': 'success',
              'message': 'User does not have a menu yet',
              'data': [{"id": user.id,
                        "seeds": user.seeds,
                        "content": template}]
            }

                        //"menu": [] //----> key, value was missing

因此,没有获取'menu'值,这就是'undefined'所指的:

//GET request at `getSeeds()`
this.setState({
        menu: res.data.data[0].menu // <----- undefined
      })

根本不能将this.state.menu设置为getSeeds()

"menu": []添加到response_object进行了修复。