【问题标题】:Solved : ReactJS : Uncaught TypeError: Cannot read property 'id' of undefined when posting to a Laravel Controller using axios已解决 : ReactJS : Uncaught TypeError: Cannot read property 'id' of undefined 使用 axios 发布到 Laravel 控制器时
【发布时间】:2020-08-24 11:23:50
【问题描述】:

我正在尝试使用 ReactJs 获取数据并将其显示为动态选择/选项菜单,并将所选值发布到 Laravel 控制器,因此我也无法存储它。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

export default class Sm extends Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            name: '',
            json:JSON.parse(props.data)
        };

        this.onChangeValue = this.onChangeValue.bind(this);
        this.onSubmitButton = this.onSubmitButton.bind(this);
    }

    onChangeValue(e) {
        this.setState({
            [e.target.name]: e.target.value
        });
    }

    onSubmitButton(e) {
        e.preventDefault();

        axios.post('/Y', {
            name: this.state.json.id//error : Uncaught TypeError: Cannot read property 'id' of undefined
        })
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            // console.log(error);
            console.log(this.state.json.id);// error: Uncaught TypeError: Cannot read property 'id' of undefined
        });

        this.setState({
            name: ''
        })
    }

    componentDidMount () {
    }

    render()
    {
        return (
            <form onSubmit={this.onSubmitButton}>
                <select>
                    {this.state.json.map(i => (
                        <option className="form-control" name="name" value={i.id} onChange={this.onChangeValue}>{i.name}</option>//the id proprty is working :/
                    ))}
                </select>
                <button className="btn btn-success">Submit</button>
            </form>
        );
    }
}

if (document.getElementById('sm')) {
    var data = document.getElementById(('sm')).getAttribute('data');
    ReactDOM.render(<Sm data={data}/>, document.getElementById('sm'));
}

一切正常,但是当我发布选择的值时,我遇到了这个错误: Uncaught TypeError: Unable to read the property 'id' of undefined,但另一方面,属性 id 是定义的,因为我可以看到它的功能那在&lt;option className="form-control" name="name" value={i.id} onChange={this.onChangeValue}&gt;{i.name}&lt;/option&gt;

我什至尝试了this.state.json.i.id 仍然是同样的问题。

-更新:我的新代码:

    import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

export default class Sm extends Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            name: '',
            json:JSON.parse(props.data)
        };

        this.onChangeValue = this.onChangeValue.bind(this);
        this.onSubmitButton = this.onSubmitButton.bind(this);
    }

    onChangeValue(e) {
        this.setState({
            [e.target.name]: e.target.value
        });
    }

    onSubmitButton(e) {
        e.preventDefault();

        axios.post('/Y', {
            name: this.state.name////500 (Internal Server Error)
        })
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            // console.log(error);
            console.log(this.state.name);//Uncaught (in promise) TypeError: Cannot read property 'state' of undefined
            //console.log(this.state);//Uncaught (in promise) TypeError: Cannot read property 'state' of undefined
            //console.log(this);//undefined
        });

        this.setState({
            name: ''
        })
    }

    componentDidMount () {
    }

    render()
    {
        return (
            <form onSubmit={this.onSubmitButton}>
                <select>
                    {this.state.json.map(i => (
                        <option className="form-control" name="name" value={i.id} onChange={this.onChangeValue}>{i.name}</option>//the id proprty is working :/
                    ))}
                </select>
                <button className="btn btn-success">Submit</button>
            </form>
        );
    }
}

if (document.getElementById('sm')) {
    var data = document.getElementById(('sm')).getAttribute('data');
    ReactDOM.render(<Sm data={data}/>, document.getElementById('sm'));
}

代码最终版本:

    import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

export default class Sm extends Component
{
    constructor(props)
    {
        super(props);
        this.state = {
            json:JSON.parse(props.data),
            name: ''
        };

        this.onChangeValue = this.onChangeValue.bind(this);
        this.onSubmitButton = this.onSubmitButton.bind(this);
    }

    onChangeValue(e) {
        this.setState({
            // [e.target.name]: e.target.value
            name: e.target.value
        });
        console.log("Am i working ?");
    }

    async onSubmitButton(e) {
        e.preventDefault();

        try {
        const response = await axios.post('/Y', {name: this.state.name});
        console.log(response.data);
        } catch (error) {
          console.log(this.state.name);
        }

        this.setState(prevState => ({...prevState, name: ''}));
      }

    componentDidMount () {
    }

    render()
    {
        return (
            <form onSubmit={this.onSubmitButton}>
                <select onChange={this.onChangeValue} >
                    {this.state.json.map(i => (
                        <option className="form-control" name="name" value={i.id}>{i.name}</option>
                    ))}
                </select>
                <button className="btn btn-success">Submit</button>
            </form>
        );
    }
}

if (document.getElementById('sm')) {
    var data = document.getElementById(('sm')).getAttribute('data');
    ReactDOM.render(<Sm data={data}/>, document.getElementById('sm'));
}

【问题讨论】:

  • props.data 中有什么内容?
  • props.data 是我使用 laravel 控制器从数据库中获取的数据

标签: javascript reactjs laravel axios


【解决方案1】:

当您选择某些内容时,您将 id 存储在 state.name 中,因此所选的 id 在这里可用并且应该可以工作。

i.id 有效,因为您在地图中。你不能做 json.id 因为 json 包含多个子对象。

所以你的 axios 请求应该是这样的:

axios.post('/Y', {name: this.state.name})
  .then(...)

[编辑]:这是您的异步​​ onSubmit 方法:

async onSubmitButton(e) {
  e.preventDefault();

  try {
    const response = await axios.post('/Y', {name: this.state.name});
    console.log(response.data);
  } catch (error) {
    console.log(this.state.name);
  }

  this.setState(prevState => ({...prevState, name: ''}));
}

【讨论】:

  • 是的,你是对的,i.id 工作只是因为它在地图内,我将 this.state.json.id 更改为 this.state.name,现在我面临一个新错误:@987654326 @ 并且在尝试查看发生了什么时,我也发现了这个问题 console.log(this.state.name);//Uncaught (in promise) TypeError: Cannot read property 'state' of undefined //console.log(this.state);//Uncaught (in promise) TypeError: Cannot read property 'state' of undefined //console.log(this);//undefined
  • @YassineGhz 你能用你的新代码更新你的帖子吗?
  • 是的,当然@Quentin Grisel,非常感谢您抽出宝贵的时间。
  • 我认为现在的问题是axios.post
  • 好像有2个问题。 1-您的 POST 请求不起作用。我不知道 axios 是如何工作的,但通常,InternalServerError 表示您的后端有问题。 2- http 请求是异步的,所以你应该使用 async.await 模式。否则,最后一个 setState 可能会在请求完成之前擦除 state.name 的值。
【解决方案2】:

您使用的是 this.state.json.map,这意味着 this.state.json 是一个数组。这就是为什么你不能使用 this.state.json.id 因为 id 不存在。如果至少有 1 个元素并且您想要访问您的数组,则第一个元素将是 this.state.json[0].id

在您的情况下,您希望获得您在 onChangeValue 中设置的值。

onChangeValue(e) {
  this.setState({
    [e.target.name]: e.target.value
  });
}

根据您的代码,您可以使用 this.state.name 检索选定的 id,因为这是您的选择输入的名称 (name="name")

【讨论】:

  • 我没有输入!我只有一个表单和一个具有
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 2020-10-25
  • 1970-01-01
  • 2013-01-15
  • 2021-03-16
  • 2019-02-12
  • 2022-10-18
  • 2021-09-20
相关资源
最近更新 更多