Javascript-форум (https://javascript.ru/forum/)
-   Библиотеки/Тулкиты/Фреймворки (https://javascript.ru/forum/library-toolkit-framework/)
-   -   обновление компонента (https://javascript.ru/forum/library-toolkit-framework/76535-obnovlenie-komponenta.html)

dmitry.suhotsky 20.01.2019 17:36

обновление компонента
 

Реализую CRUD. Требуется отобразить в полях выбранное значение, изменит и сохранить обратно.

Передаю измененное значение в компонент, и если значение предыдущих props отлично от значения текущего стейт, запускаю функцию update


componentDidUpdate(prevProps) {
        if (this.props.selectItem !== prevProps.selectItem) {
            this.update();
        }
    }
    update = () => {
        this.setState({ selectItem: this.props.selectItem  })
        console.log(this.state.selectItem)
    }

Выводу текущий стейт в лог - новый state отображается, но в инпутах значения не изменяются. В предыдущем показали реализацию CreateElementa, вопрос, это единственный метод для реализации? и почему при измененном стейте значения не изменились?

import React, { Component } from 'react';
import './App.css';
import Table from './component/Table'
import ReadItem from './component/read/ReadItem'
import { Provider } from './component/service-contex/service-contex'

class App extends Component {

  state = {
    mobile : [
      {"id": 1, "name": "Dima", "phone": 12345},
      {"id": 2, "name": "Ira", "phone": 67890},
    ],
    selectItem: 
      {"name": null,
    "phone": null}
    
  }
  deleteItem = (id) => {
    console.log(id);
    const newMobile = this.state.mobile.filter((el) => el.id !== id )
    this.setState({
      mobile: newMobile
    })
  }
  updateItem = (id) => {
    console.log(id);
    const selectItem = this.state.mobile.filter((el) => el.id === id )
    this.setState({
      selectItem: selectItem
    })
  }
  render() {
    return (
      <Provider value={this.state}>
        <Table deleteItem={this.deleteItem}
               updateItem={this.updateItem}/>
        <ReadItem  selectItem={this.state.selectItem}/>
      </Provider>
    );
  }
}

export default App;


import React, { Component } from 'react';
import { Consumer } from './service-contex/service-contex'
class Table extends Component {
    delItem = (id) => {
        this.props.deleteItem(id);
    }
    update = (id) => {
        this.props.updateItem(id);
    }

    render() {
        return (
            <table>
                <Consumer>
                    {contex => {
                        return (
                            contex.mobile.map((item, index) => {
                                return (
                                    <tr key={index}>
                                        <th>{item.id}</th>
                                        <th>{item.name}</th>
                                        <th>{item.phone}</th>
                                        <th><button  onClick={() => this.update(item.id)}>P</button><button onClick={() => this.delItem(item.id)}>X</button></th>
                                    </tr>)
                            })
                        )
                    }
                    }
                </Consumer>

            </table>
        );
    }
}

export default Table;


import React, { Component } from 'react';

class ReadItem extends Component {
    constructor(props) {
        super(props);

    this.state = {
        selectItem: 
        {"name": null,
        "phone": null}
    }
    }
    componentDidUpdate(prevProps) {
        if (this.props.selectItem !== prevProps.selectItem) {
            this.update();
        }
    }
    update = () => {
        this.setState({ selectItem: this.props.selectItem  })
        console.log(this.state.selectItem)
    }
    render() {
        return (
            <>
                <div> Name 
                    <input defaultValue={this.state.name}></input>
                </div>
                <div> Phone
                    <input defaultValue={this.state.phone}></input>
                </div>
                <div>
                    <button>Save</button>
                    <button>Cancel</button>
                </div>
            </>
        )
    }
}

export default ReadItem;

dmitry.suhotsky 20.01.2019 19:10

Пытаюсь через
<div> Name 
                    <input ref="name" ></input>
                </div>
                <div> Phone
                    <input ref="phone" ></input>
                </div>

update = () => {
        this.setState({ selectItem: this.props.selectItem  })
        this.refs.name.value =this.props.selectItem.name
        this.refs.phone.value = this.props.selectItem.phone
       
    }

но тщетно

dmitry.suhotsky 20.01.2019 19:27

Input стал отображать верные данные выбранных послей, после

this.refs.name.value = this.props.selectItem[0].name
        this.refs.phone.value = this.props.selectItem[0].phone

Объясните почему

dmitry.suhotsky 20.01.2019 22:20

Вопрос 2.
Пытаюсь обновить данные следующим способом

saveItem = (text,phone,id) => {
    let NewArr = this.state.mobile;
    NewArr = NewArr.map(el => {
      if (el.id === id) {
        el.name = text;
        el.phone = phone
      }
      return NewArr;
    })
    this.setState({
      mobile: NewArr,
      read: false
    })
    // const newItem = {
    //   id: id,
    //   name: text,
    //   phone: phone
    // }
    // let NewArray = this.state.mobile.filter(el => el.id === id);
    // NewArray = newItem;
    // const NewMobile = this.state.mobile;
    // NewMobile[index] = NewArray;
    // this.setState({
    //   mobile: NewMobile
    
    // })
  }

Первым способом ошибка, в масиве NewArr - там появляется в каждом NewArr[i] по два элемента стейта
Во втором закомментированном не знаю как найти индекс NewMobile[index]. Скорее всего в filter, по как передать наружу не получается


Часовой пояс GMT +3, время: 14:02.