2017-07-07 18 views
1

私はreact-sortable-hocを使ってサンプルを試しています。ソート可能なソートはソート時に状態を保持できません。 GIFを見てください。以下はreact-sortable-hoc reactJSライブラリのソート問題

enter image description here

import React, {Component} from 'react'; 
import {SortableContainer, SortableElement, arrayMove} from 'react-sortable- 
hoc'; 
// Css 
import './object_library.css' 

const SortableItem = SortableElement(({value}) => 
<div className="Showcase_test_horizontalItem" > 
    <div>{value}</div> 
    <br /> 
    <TestSortable /> 
</div> 
); 

const SortableList = SortableContainer(({items}) => { 
return (
    <div> 
     {items.map((value, index) => (
      <SortableItem key={`item-${index}`} index={index} value={value} 
/> 
     ))} 
    </div> 
); 
}); 

class TestSortable extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     sum: 0 
    } 
    this.onAddChild = this.onAddChild.bind(this) 
} 
onAddChild() { 
    let prevSum = this.state.sum + 1; 
    this.setState({ 
     sum: prevSum 
    }); 
} 
render() { 
    return (
     <div> 
      <div> {this.state.sum} </div> 
      <button className="my_plus_buttons" onClick={this.onAddChild}>+ 
      </button> 
     </div> 
    ); 
    } 
} 

class SortableComponent extends Component { 
state = { 
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'], 
}; 
onSortEnd = ({oldIndex, newIndex}) => { 
    this.setState({ 
     items: arrayMove(this.state.items, oldIndex, newIndex), 
    }); 
}; 
render() { 
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} 
    axis="x"/>; 
    } 
} 

export default SortableComponent; 

ないこのライブラリは状態を維持していない理由を確認してください..私のサンプルコードですか?

おかげで、あなたのSortableListで

答えて

0

は、あなたが行うには、通常のものであるが、問題を引き起こすものであると思われる現在のインデックスに基づいて、キーを設定しています。代わりにキーを値に一致させると、期待どおりに動作するように見えます。

私は、基になるコンポーネントでキーを移動する必要があると思います。

const SortableList = SortableContainer(({ items }) => { 
    return (
    <div> 
     {items.map((value, index) => (
     <SortableItem key={`item-${value}`} index={index} value={value} /> 
    ))} 
    </div> 
); 
}); 
+0

ありがとうございます! SortableItemの中にキーがない – HarshMakadia