首页 > 解决方案 > 尝试通过道具向子级提升功能时超出最大更新深度

问题描述

我在我的主要组件中保存了一个 json 数组,并且我创建了一个保存输入的“FormComponent”。

我在父组件中创建了一个“添加”函数,我正试图通过名称下的 prop 将它发送给子组件,createTODOhander如您在此处看到的:

import * as React from "react";
import Task from "./Task";
import FormComponent from "./FormComponent";


class TodoList extends React.Component {
    state = {
        MAXIMUMJOBS: 5,
        TodoList: [],
    }
    createTODO = (Todoname) => {
        this.setState({
            TodoList: this.state.TodoList.concat({Todoname: Todoname})
        })
    }
    render() {
        return (
            <div style={{marginLeft: '10px'}}>
                <h3>You can enter {this.state.MAXIMUMJOBS - this.state.TodoList.length} TODO list jobs.</h3>
                <FormComponent createTODOhandler={this.createTODO()} />
            )
    }
}

FormComponent我试图以这种方式使用它:

import * as React from "react";


class FormComponent extends React.Component {
    state = {
        inputValue: ''
    }
    inputChanged = (e) => {
        this.setState({
            inputValue: e.target.value
        })
    };
    createTODO = () => {
        if (this.state.inputValue === '') {}//do nothing, not gonna happen because the button is disabled.
        else{
            this.props.createTODOhandler(this.state.inputValue);
        }
    };
    render() {
        return (
            <div>
                <input type="text" onChange={this.inputChanged} value={this.state.inputValue}
                       placeholder={"Enter your job here."}/>
                &nbsp;
                <button onClick={this.createTODO}>Add!</button>
                &nbsp;
                <button>Clear list</button>
            </div>
        )
    }
}

export default FormComponent;

但我得到一个Maximum update depth exceeded.错误,

谢谢你的帮助。

标签: reactjsjsx

解决方案


应该()从道具中移除。

这个<FormComponent createTODOhandler={this.createTODO()} />

变成:<FormComponent createTODOhandler={this.createTODO} />


推荐阅读