将数据推送到数组时,React功能组件未更新

时间:2019-05-15 19:13:47

标签: reactjs components react-component

我有这个功能组件,当将数据推送到数组时不会更新:

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>
        </>
    )
}

单击添加体验后,映射没有更新,是否有帮助?

1 个答案:

答案 0 :(得分:3)

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

为了获得所需的行为,必须使用状态,或者使用useState钩子,或者使用带有状态的类组件。

带有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>
        </>
    )
}

类组件

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>
        </>
    )
}