【发布时间】:2019-01-18 09:48:59
【问题描述】:
基本上我试图在对象数组中移动单个对象,但是当我移动同一个对象一次或两次时,它开始移动所述数组中的另一个对象。
所以我尝试用 .slice() 然后 .shift(item) 按它的索引创建一个新数组,然后用 .splice(newIndex, 0, item) 将它添加回正确的索引,一旦数组有一直在更新,我将它推送到 Redux 商店,它会更新我的 Megadraft(即 Draft.js)应用程序。
我也尝试过直接操作原始数组,即 this.props.array(就像你对 Redux 的意思一样)并使用对象内部的键而不是索引。
import React from 'react';
import { MegadraftPlugin, DraftJS, CommonBlock } from "megadraft"
export default class ImageGalleryBlock extends React.Component {
_moveImgOneBack = (e, images, index) =>{
e.preventDefault()
let newPlace = index - 1
if(newPlace == -1){
newPlace = images.length
}
const image = images.shift(index)
images.splice(newPlace, 0, image)
return this.props.container.updateData({ images: images })
}
_moveImgOneForward = (e, images, index) =>{
e.preventDefault()
let newPlace = index +1
if(newPlace > images.length){
newPlace = 0
}
const image = images.shift(index)
images.splice(newPlace, 0, image)
return this.props.container.updateData({ images: images })
}
render(){
return (
<CommonBlock {...this.props} actions={this.actions} title="Image
Gallery">
<BlockContent>
<div className='gallery-cms-block'>
{ this.props.images.map((obj, index)=> {
return(
<div key={obj.key} className="image-box">
<button title="Move image back one" className="move-button"
onClick={(e)=> this._moveImgOneBack(e,
this.props.data.images, index)}>◀ {index}</button>
<img className="image" src={`${obj.image.uri}?
id=${obj.image.id}`} />
<div>
<button key={obj.key} title="Move image forward one"
className="move-button" onClick={(e)=>
this._moveImgOneForward(e, this.props.data.images,
index)}>▶</button>
</div>
</div>
)
}) }
</div>
</BlockContent>
</CommonBlockMKII>
);
}
}
我希望按钮(向前或向后)移动所述项目并且仅移动所述项目。
结果是它会移动该项目一次......也许两次然后移动数组中的所有其他项目。
【问题讨论】:
标签: reactjs redux ruby-on-rails-5 draftjs