не обновляются input из state
![]() Реализую CRUD приложение. Добавление и удаление реализовал. Возник вопрос с обновлением. Для этого: 1) При нажатии кнопки "Редакт" передаю в компанент `App` `item.id` элемента, который предстоит отредактировать и загрузить снова. 2) Нахожу, фильтрую и пишу в стейт readItem = (id) => { const readItem = this.state.auto.filter((el) => el.id === id) this.setState({readItem}) } 3) Передаю значения в дочерний компонент <Header readItem={this.state.readItem}/> 4) В дочернем элементе меняю стейт, он приходит и в dev tools видно что менятся state на переданные значения, но значения в инпутах не отображается constructor(props) { super(props); this.state = { id: this.props.readItem.id, name: this.props.readItem.name, marka: this.props.readItem.marka, country: this.props.readItem.country, price: this.props.readItem.price, url: this.props.readItem.url } } инпут <input name="name" value={name} onChange={this.inputName} placeholder="Название" /> Ниже представленные компаненты: App import React, { Component } from 'react'; import './App.css'; import Header from './component/Header/Header' import ListAuto from './component/ListAuto/ListAuto' import EditItems from './component/Edit/EditItems' class App extends Component { state = { auto: [ { "id": 1, "name": "Авто №1", "marka": "Марка машины №1", "price": 50, "country": "Russia", "url": "https://finance.liga.net/images/general/2018/08/29/thumbnail-tw-20180829113845-1826.jpg" }, { "id": 2, "name": "Авто №2", "marka": "Марка машины №2", "price": 20, "country": "Russia", "url": "https://icdn.lenta.ru/images/2017/08/23/14/20170823145604779/pic_b21fd6a6551e45ce4a397c3c2662ec8f.jpg" }, ], readItem: [{ "id": null, "name": null, "marka": null, "price": null, "country": null, "url": null }] } addItem = (item) => { const addAuto = { id: this.state.auto.length + 1, name: item.name, marka: item.marka, price: item.price, country: item.country, url: item.url } this.setState(({ auto }) => { const NewArray = [ ...auto, addAuto ] return { auto: NewArray } }) } delItem = (id) => { const NewArr = this.state.auto.filter((el) => el.id !== id) this.setState({ auto: NewArr }) } readItem = (id) => { const readItem = this.state.auto.filter((el) => el.id === id) this.setState({readItem}) } render() { const { auto } = this.state; return ( <div className="App"> <Header addItem={this.addItem} readItem={this.state.readItem}/> <EditItems ArrayAutoForRead={auto} delItemId={this.delItem} readItemId={this.readItem} /> <ListAuto ArrayAuto={auto} /> </div> ); } } export default App; Header import React, { Component } from 'react'; class Header extends Component { constructor(props) { super(props); this.state = { id: this.props.readItem.id, name: this.props.readItem.name, marka: this.props.readItem.marka, country: this.props.readItem.country, price: this.props.readItem.price, url: this.props.readItem.url } } componentWillReceiveProps(nextProps) { if (this.props.readItem !== nextProps.readItem) { this.setState({ state: nextProps.readItem }) } } addItem = () => { const { name, marka, country, price, url } = this.state; if (name !== "" && marka !== "" && country !== "" && price !== "" && url !== "") { const item = { name, marka, country, price, url } this.props.addItem(item) this.setState({ name: "", marka: "", country: "", price: "", url: "" }) } else { alert('Заполните все поля') } } inputName = (e) => { const name = e.target.value; this.setState({ name }) } inputMarka = (e) => { const marka = e.target.value; this.setState({ marka }) } inputCountry = (e) => { const country = e.target.value; this.setState({ country }) } inputPrice = (e) => { const price = e.target.value; this.setState({ price }) } inputUrl = (e) => { const url = e.target.value; this.setState({ url }) } render() { const { name, marka, country, price, url } = this.state; return ( <div className="Header"> Header menu <input name="name" defaultValue={name} onChange={this.inputName} placeholder="Название" /> <input name="marka" defaultValue={marka} onChange={this.inputMarka} placeholder="Марка" /> <input name="country" defaultValue={country} onChange={this.inputCountry} placeholder="Производитель" /> <input name="price" defaultValue={price} onChange={this.inputPrice} placeholder="Цена" /> <input name="url" defaultValue={url} onChange={this.inputUrl} placeholder="url картинки" /> <button onClick={this.addItem}>Добавить</button> </div> ); } } export default Header; EditItems import React, { Component } from 'react'; import './style.css' class EditItems extends Component { delItem = (id) => { this.props.delItemId(id) } readItem = (id) => { this.props.readItemId(id) } render() { const {ArrayAutoForRead} = this.props return ( <div className="EditItems"> Редактирование данных <table > <thead> <tr> <th>Id</th> <th>Название</th> <th>Марка</th> <th>Производитель</th> <th className="th">url фото</th> <th>Цена</th> <th>Действие</th> </tr> </thead> <tbody> { ArrayAutoForRead.map( (item,index) => { return ( <tr rey={index}> <th>{item.id}</th> <th>{item.name}</th> <th>{item.marka}</th> <th>{item.country}</th> <th className="th">{item.url}</th> <th>{item.price}</th> <th><button onClick={() => this.readItem(item.id)}>Редакт</button><button onClick={() => this.delItem(item.id)}>X</button></th> </tr> ) }) } </tbody> </table> </div> ); } } export default EditItems; ListAuto import React, { Component } from 'react'; import ItemAuto from '../ItemAuto/ItemAuto' class ListAuto extends Component { render() { return ( <> { this.props.ArrayAuto.map((item, index) => { return ( <div className="ListAuto"> <ItemAuto key={index} itemAuto={item} /> </div> ) }) } </> ); } } export default ListAuto; |
<iframe src="https://codesandbox.io/embed/xr3l5lnl24?hidenavigation=1&module=%2Fsrc%2Fapp.js&view=preview" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe> Найденные ошибки: key или rey? td или th? в самый первый раз можно добавить пустое? но ведь вы проверяете на пустую строку! "" vs undefined this.state = { ...this.props.readItem } или руками всё перечислять? name !== "" && marka !== "" && country !== "" && price !== "" && url !== "" vs [name, marka, country, price, url].every(p => p !== "") this.props.readItem массив, а вы работаете с ним как с элементом этого массива {} vs [{}] Сравните свой код с отредактированным! https://codesandbox.io/s/xr3l5lnl24 |
Часовой пояс GMT +3, время: 09:00. |