将数据推送到数组时反应功能组件不更新

React functional component not updating when pushing data to array

我有这个功能组件,它在将数据推送到数组时没有更新:

const Experience = (props) => {
    let experience = [{
        from:"", 
        to:"",
        employer_name:"",
        employer_number:""
    }];

    function addExperience() {
        experience = [...experience, {
            from:"", 
            to:"",
            employer_name:"",
            employer_number:"",
        }];
    }

    return (
        <>
            {experience.map((val, idx) => {
                let id = `exp-id-${idx}`

                return(
                    <div key={idx} id={id}>
                        ...
                    </div>
                )
            })}
            <button onClick={addExperience}>Add experience</button>
        </>
    )
}

点击添加体验后映射没有更新,有什么帮助吗?

虽然您正在更新变量,但组件本身并没有重新呈现。功能组件将在其道具之一更新时触发渲染。

为了获得所需的行为,您必须使用状态,通过 useState 挂钩或使用带状态的 class 组件。

带有 React Hooks 的功能组件

import React, { useState } from 'react';

const Experience = (props) => {
    const [experience, setExperience] = useState([{
        from:"", 
        to:"",
        employer_name:"",
        employer_number:""
    }]);

    function addExperience() {
        setExperience([...experience, {
            from:"", 
            to:"",
            employer_name:"",
            employer_number:"",
        }]);
    }

    return (
        <>
            {experience.map((val, idx) => {
                let id = `exp-id-${idx}`

                return(
                    <div key={idx} id={id}>
                        ...
                    </div>
                )
            })}
            <button onClick={addExperience}>Add experience</button>
        </>
    )
}

Class 组件

import React, { Component } from 'react'

class Experience extends Component {
    state = {
        experience: [{
            from:"", 
            to:"",
            employer_name:"",
            employer_number:""
        }]
    };

    function addExperience() {
        this.setState([...this.state.experience, {
            from:"", 
            to:"",
            employer_name:"",
            employer_number:"",
        }]);
    }

    return (
        <>
            {this.state.experience.map((val, idx) => {
                let id = `exp-id-${idx}`

                return(
                    <div key={idx} id={id}>
                        ...
                    </div>
                )
            })}
            <button onClick={this.addExperience}>Add experience</button>
        </>
    )
}