K
K
Komi7ar2020-12-22 17:05:20
React
Komi7ar, 2020-12-22 17:05:20

I can't understand why they get an error while trying to change an object?

It is required to dynamically update the data inside the table when entering data into the

handler inputs

import { bool } from 'prop-types';
import React from 'react'
import {connect} from "react-redux"
import {createNewUser, deleteUser, changeInfo} from "../components/redux/action"


class SecondWindow extends React.Component{
    constructor(props){
        super(props);
        
         
    }
    
    
    handleOptionChange = e => {
        this.setState(
            {
                selectedOption:e.target.value
            }
        )
    }

    submitHandler = e => {
        e.preventDefault();        

        const newUser = {
            id: Date.now().toString(),
            FIO: "Имя",
            position:"Должность",
            birthDay: "год/месяц/день",
            sex: true ,
            fired: false
        };
        console.log(this.props);
        this.props.createNewUser(newUser);
    }

    // changeInputHandler = e => {
    //     e.persist();
    //     this.setState(prev=>({...prev, ...{
    //         [e.target.name]: e.target.value
    //     }}))
    // }
    changeInputHandler = ({ target: t }) => {
        this.setState(state => ({
          ...state,
          [t.name]: t.type === 'checkbox' ? t.checked : t.value,
        }));
        

        const valueForUpdate = {
            id: this.props.items.activeUser.id,
            box: t.name,
            newValue: t.type === 'checkbox' ? t.checked : t.value
        };
        
        this.props.changeInfo(valueForUpdate);
      }

    isFormValid = () => {
        const {FIO, position, birthDay, sex, fired} = this.state;
        console.log(FIO && position && birthDay && sex && fired);
        return FIO && position && birthDay && sex && fired 
    }

    deleteUser = () => {
        this.props.deleteUser(this.props.items.activeUser);
        
    }
    

    render() {
        return (
            <form onSubmit={this.submitHandler}>
                <div className="input-group mb-3">                    
                    <input type="text" className="form-control" placeholder="ФИО"
                    name="FIO" 
                    onChange={this.changeInputHandler}
                    value={this.props.items.activeUser.FIO}
                    ></input>
                </div>
                <select className="form-select" aria-label="Default select example"
                name ="position"
                onChange={this.changeInputHandler}
                value={this.props.items.activeUser.position}> 
                    <option defaultValue = "Выбирите должность">Выбирите должность</option>       
                    <option value="Старший разработчик">Старший разработчик</option>
                    <option value="Младший разработчик">Младший разработчик</option>
                    <option value="Эйчар">Эйчар</option>
                    <option value="Уборщик">Уборщик</option>
                </select>

                <div className="form-group ">                
                    <div className="mb-3"></div>
                        <input className="form-control" type="date"  id="example-date-input"
                        name ="birthDay"
                        onChange={this.changeInputHandler}
                        value={this.props.items.activeUser.birthDay}></input>  
                </div>
              


               
                <div className="form-check">
                    <input className="form-check-input" type="radio" name="flexRadioDefault"
                     id="flexRadioDefault1"
                     value ="М"
                     name ="sex"
                     onChange={this.changeInputHandler}
                     checked={this.props.items.activeUser.sex}
                    ></input>
                    <label className="form-check-label" htmlFor="flexRadioDefault1">
                    М
                    </label>
                </div>
                <div className="form-check">
                    <input className="form-check-input" type="radio" name="flexRadioDefault"
                    id="flexRadioDefault1"
                    value ="Ж"
                    name ="sex"
                    onChange={this.changeInputHandler}
                    checked={!this.props.items.activeUser.sex}
                    ></input>
                    <label className="form-check-label" htmlFor="flexRadioDefault1">
                    Ж
                    </label>
                
                </div>

                
                
                <div className="form-check">
                    <input className="form-check-input" type="checkbox"  id="flexCheckDefault"
                    name ="fired"
                    onChange={this.changeInputHandler}
                    checked={this.props.items.activeUser.fired}
                    ></input>
                    <label className="form-check-label" htmlFor="flexCheckDefault">
                    Уволен
                    </label>
                </div>
                <button type="button" className="btn btn-success" onClick = {this.submitHandler}
                 disabled = {!this.isFormValid}
                 >Добавить нового сотрудника</button>
                <button type="button" className="btn btn-danger"
                 onClick = {this.deleteUser}>Удалить выбранного сотрудника</button>  
            </form>
        );
    }
}

const mapStateToProps = state => {
    console.log(state.items.items);
    return {
        items: state.items,

    }
}

const mapDispatchToProps = {
    createNewUser: createNewUser,
    deleteUser:deleteUser,
    changeInfo:changeInfo
}

export default connect(mapStateToProps, mapDispatchToProps)(SecondWindow);


edit code.
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case CREATE_NEW_USER:            
            return {...state, items: state.items.concat([action.payload])}
        
        case DELETE_USER:
            return {...state, items: state.items.filter((item)=>{
                return item.id !== action.payload.id;
            })
        }
        case USER_INFO:
            return {...state, activeUser: action.payload}

        case CHANGE_INFO:
            return {...state, items: state.items.forEach((item)=>{ // если использовать forEach получаю ошибку 1, если map то 2
                if(item.id === action.payload.id){  
                    console.log(item) 
                    console.log(action.payload.id, item[action.payload.box], action.payload.newValue);                 
                    item[action.payload.box] = action.payload.newValue
                }
            })
        }
       

        default:
            return state;
    }
    
}


Action
export function changeInfo(item) {
    return {
        type: CHANGE_INFO,
        payload: item
    }
}


Error 1
×
TypeError: Cannot read property 'map' of undefined
FirstWindow
E:/Важно/web/dev/greenData/green-data/src/components/FirstWindow.js:18
  15 | 
  16 | const [active, setActive] = React.useState(null);
  17 | return(
> 18 |     <div className = "container">
     | ^  19 |         {
  20 |             items.items.map((item,i) =>{
  21 |                 return <FirstWindowItems
View compiled
▶ 28 stack frames were collapsed.


Mistake 2
×
TypeError: Cannot read property 'id' of undefined
(anonymous function)
E:/Важно/web/dev/greenData/green-data/src/components/FirstWindow.js:21
  18 | <div className = "container">
  19 |     {
  20 |         items.items.map((item,i) =>{
> 21 |             return <FirstWindowItems
     | ^  22 |              item = {item}
  23 |              isActive={active===i}
  24 |              onClick={()=>getElem(i,item)}
View compiled

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question