Pad*_*eti 5 setstate reactjs sortablejs
我正在尝试建立一个“将单词按顺序排列”的典型语言学习活动。用户应该首先将句子的第一个单词拖到正确的位置,然后从那里继续。同时,我正在检查下一个单词是否在正确的位置。如果是这样,该单词/项目将更改 CSS 类,并且变得不可拖动并且具有不同的背景颜色。
为了发生此 CSS 类更改,我克隆可拖动的单词列表,进行必要的更改,然后使用新的更新列表设置 State()。这就是我遇到问题的时候。列表和组件偶尔会更新,似乎是随机的。当我尝试更新 handleDragEnd() 方法中的单词列表时,我一定做错了什么。这是代码的一部分:
export default class Sentence extends Component {
constructor(props) {
super (props)
// prepare this.state.list to be used by SortableJS
let list = this.props.sentenceShuffled.map((word, index) => {
return { id: (++index).toString(), name: word, class: 'sortable' }
})
this.state = {
currentCorrectWord: 0, // stores how many words are correct already while student is sorting
complete: false, // becomes true when sentence is sorted
list: list // this object is used by SortableJS and is calculated in componentWillMount
}
this.handleDragEnd = this.handleDragEnd.bind(this)
}
handleDragEnd() {
let currentCorrectWord = this.state.currentCorrectWord
while ( this.state.list[currentCorrectWord].name === this.props.sentenceInOrder[currentCorrectWord]) {
let newList = _.cloneDeep(this.state.list)
newList[currentCorrectWord].class = 'notSortable'
currentCorrectWord++
/*
this is where (I think) the problem is: setSate won't update states nor re-render component.
*/
this.setState({ currentCorrectWord: currentCorrectWord })
this.setState({ list: newList })
... more code here
}
}
render() {
return (
...more code here
<ReactSortable
list={this.state.list}
setList={newState => this.setState({ list: newState })}
filter=".notSortable"
>
{this.state.list.map(item => (
<MDBBox
className={item.class + ' eachWord'}
key={item.id}
onDragEnd={this.handleDragEnd}
>{item.name}
</MDBBox>
))}
</ReactSortable>
...more code here
)
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
| 归档时间: |
|
| 查看次数: |
796 次 |
| 最近记录: |