简体   繁体   中英

React TypeError: this.state.descriptions.map is not a function

I'm trying to fix this error 在此处输入图片说明

What I'm trying to do is to render an automated form which is built by this function:

let descriptionsForm = (
        <form>
        {this.state.descriptions.map((description, index) => (
            <Input
                key={index}
                elementType={description.elementType}
                elemenyConfig={description.elementConfig}
                value={description.value}
                invalid={!description.valid}
                shouldValidate={description.validation}
                touched={description.touched}
                changed={(event) => this.descriptionInputChangedHandler(event, index)}
                />
        ))}
        </form>
    )

It works when first time opening the page, but when I tried to type something in that Input tab, the error shows up.

Here's the descriptionInputChangedHandler function:

descriptionInputChangedHandler = (event, index) => {
    console.log("ORIGINAL: ", this.state.descriptions)
    const updatedDescriptions = {
        ...this.state.descriptions
    };

    const updatedDescriptionElement = {
        ...updatedDescriptions[index]
    };
    updatedDescriptionElement.value = event.target.value;
    updatedDescriptionElement.valid = this.checkValidity(updatedDescriptionElement.value, updatedDescriptionElement.validation);
    updatedDescriptionElement.touched = true;
    updatedDescriptions[index] = updatedDescriptionElement;

    let formIsValid = true;
    for (let index in updatedDescriptions) {
        formIsValid = updatedDescriptions[index].valid && formIsValid;
    }
    console.log("UPDATED D: ", updatedDescriptions);

    this.setState({descriptions: updatedDescriptions, descriptionFormIsValid: formIsValid})
}

the console.log()s looks like this, which I assume should be correct

在此处输入图片说明

I imagine since the input slot was rendered properly when launching, should be something happened when updating the data, which I have no idea of.

Thanks for any help.

ORIGINAL is an array, UPDATED D is an object.

    const updatedDescriptions = {
       ...this.state.descriptions
    };

should be:

    const updatedDescriptions = [
       ...this.state.descriptions
    ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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