简体   繁体   English

当尝试向现有项目中添加新任务时,Laravel + React返回错误

[英]Laravel + React returns an error when tried to add a new task to an existing Project

I just learning react programming, but I kinda stuck with this error, and I already googled it but it seems I still missing some point, can someone help me with this kinda problem? 我只是在学习反应编程,但是我一直卡在这个错误中,并且已经在Google上搜索了一下,但是似乎我仍然遗漏了一点,有人可以帮助我解决这个问题吗?

This the error I got after I tried add a new task. 我尝试添加新任务后遇到的错误。

在此处输入图片说明

Here is the JSX file, 这是JSX文件,

import axios from 'axios'
import React, { Component } from 'react'

class SingleProject extends Component {
    constructor (props) {
        super(props)

        this.state = {
            project: {},
            tasks: [],
            title: '',
            errors: [],
        }

        this.handleMarkProjectAsCompleted = this.handleMarkProjectAsCompleted.bind(this)
        this.handleFieldChange = this.handleFieldChange.bind(this)
        this.handleAddNewTask = this.handleAddNewTask.bind(this)
        this.hasErrorFor = this.hasErrorFor.bind(this)
        this.renderErrorFor = this.renderErrorFor.bind(this)
    }

    handleMarkProjectAsCompleted () {
        const { history } = this.props

        axios.put(`/api/projects/${ this.state.project.id }`)
            .then(response => {
                history.push('/')
            })
            .catch(error => {
                this.setState({
                    errors: error.response.data.errors
                })
            })
    }

    handleMarkTaskAsCompleted (taskId) {
        axios.put(`/api/tasks/${ taskId }`).then(response => {
            this.setState(prevState => ({
                tasks: prevState.tasks.filter(task => {
                    return task.id !== taskId
                })
            }))
        })
    }

    handleFieldChange (event) {
        this.setState({
            title: event.target.value
        })
    }

    handleAddNewTask (event) {
        event.preventDefault()

        const task = {
            title: this.state.title,
            project_id: this.state.project.id
        }

        axios.post('/api/tasks', task)
            .then(response => {
                this.setState({
                    title: '',
                })
                this.setState(prevState => ({
                    tasks: prevState.tasks.concat(response.data)
                }))
            })
            .catch(error => {
                this.setState({
                    errors: error.response.data.errors
                })
            })
    }

    hasErrorFor (field) {
        return !!this.state.errors[field]
    }

    renderErrorFor (field) {
        if (this.hasErrorFor(field)) {
            return (
                <span className='invalid-feedback'>
                    <strong>{ this.state.errors[field][0] }</strong>
                </span>
            )
        }
    }

    componentDidMount () {
        const projectId = this.props.match.params.id

        axios.get(`/api/projects/${ projectId }`)
        .then(response => {
            this.setState({
                project: response.data,
                tasks: response.data.tasks,
            })
        })
        .catch(error => {
            console.log(error.response.data.message);
        });
    }

    render () {
        const { project, tasks } = this.state

        return (
            <div className='container py-4'>
                <div className='row justify-content-center'>
                    <div className='col-md-8'>
                        <div className='card'>
                            <div className='card-header'>{ project.name }</div>
                            <div className='card-body'>
                                <p>{ project.description }</p>

                                <button
                                    className='btn btn-primary btn-sm'
                                    onClick={ this.handleMarkProjectAsCompleted }
                                >
                                    Mark as completed
                                </button>

                                <hr />

                                <form onSubmit={ this.handleAddNewTask }>
                                    <div className='input-group'>
                                        <input
                                            type='text'
                                            name='title'
                                            className={ `form-control ${ this.hasErrorFor('title') ? 'is-invalid' : '' }` }
                                            placeholder='Task title'
                                            value={ this.state.title }
                                            onChange={ this.handleFieldChange }
                                        />
                                        <div className='input-group-append'>
                                            <button className='btn btn-primary'>Add</button>
                                        </div>
                                        { this.renderErrorFor('title') }
                                    </div>
                                </form>

                                <ul className='list-group mt-3'>
                                    { tasks.map(task => (
                                        <li
                                            className='list-group-item d-flex justify-content-between align-items-center'
                                            key={ task.id }
                                        >
                                            { task.title }

                                            <button
                                                className='btn btn-primary btn-sm'
                                                onClick={ this.handleMarkTaskAsCompleted.bind(this, task.id) }
                                            >
                                                Mark as completed
                                            </button>
                                        </li>
                                    )) }
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

export default SingleProject

And here is the controller that handle the storing 这是处理存储的控制器

<?php

namespace App\Http\Controllers;

use App\Task;

use Illuminate\Http\Request;

class TaskController extends Controller
{
    public function store(Request $request)
    {
        $validatedData = $request->validate(['title' => 'required']);

        $task = Task::create([
            'title' => $validatedData['title'],
            'project_id' => $request->input('project_id'),
        ]);

        return $task->toJson();
    }

    public function markAsCompleted(Task $task)
    {
        $task->is_completed = true;
        $task->update();

        return response()->json('Task updated!');
    }
}

Why does the react can't find the title variable. 为什么反应无法找到标题变量。 what i do wrong in here? 我在这里做错了什么? thank you in advance 先感谢您

EDIT: 编辑:

the suspect that bring an error 带来错误的嫌疑人

在此处输入图片说明

I just found the problem, it's not coming from the JSX file, it's coming from the Task model, 我刚刚发现了问题,它不是来自JSX文件,而是来自Task模型,

在此处输入图片说明

I mistyped the project_id field, so Laravel refuse the mass assign data, that returns an internal server error. 我输错了project_id字段,因此Laravel拒绝了批量分配数据,这将返回内部服务器错误。

after I fix the typo, the error dissapeared :D 解决错字后,错误消失了:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM