根据ID编辑React中对象数组中的属性

Edit a property in an array of objects in React based on an ID

我在新 "Context API" 中创建了一个对象数组,就像这样...

const reducer = (state, action) => {
    switch (action.type) {
        case "DELETE_CONTACT":
            return {
                ...state,
                contacts: state.contacts.filter(contact => {
                    return contact.id !== action.payload;
                })
            };
        default:
            return state;
    }
};

export class Provider extends Component {
    state = {
        contacts: [
            {
                id: 1,
                name: "John Doe",
                email: "jhon.doe@site.com",
                phone: "01027007024",
                show: false
            },
            {
                id: 2,
                name: "Adam Smith",
                email: "adam.smith@site.com",
                phone: "01027007024",
                show: false
            },
            {
                id: 3,
                name: "Mohammed Salah",
                email: "mohammed.salah@site.com",
                phone: "01027007024",
                show: false
            }
        ],
        dispatch: action => {
            this.setState(state => reducer(state, action));
        }
    };

    render() {
        return (
            <Context.Provider value={this.state}>
                {this.props.children}
            </Context.Provider>
        );
    }
}

我想在 "reducer" 中创建一个操作,允许我根据我将作为有效负载传递给操作的 ID 编辑每个联系人的 "show" 属性,我该怎么做?

您可以找到联系人,使用spread避免突变,设置show的新值:

case "EDIT_CONTACT":
    const { id, show } = action.payload; // Assume id and show are in action.payload
    const contact = { ...state.contacts.find(c => c.id === id), show };
    return {
        ...state,
        contacts: [...state.contacts.filter(c => c.id !== id), contact]
    };

如果顺序很重要:

    const { id, show } = action.payload; 
    const contact = { ...state.contacts.find(c => c.id === id), show };
    const index = state.contacts.findIndex(c => c.id === id);
    return {
            ...state,
            contacts = [ ...state.contacts.slice(0, index), contact, ...state.contacts.slice(index + 1)];
    }

为避免数组突变并在编辑联系人时保留元素位置,您可以这样做:

case "EDIT_CONTACT":
    const { id, show } = action.payload;
    const contact = { ...state.contacts.find(c => c.id === id), show };
    return {
       ...state,
       contacts: state.contacts.map(c => {return (c.id !== id) ? c : contact;})        
    };