我正在尝试建立一种“按顺序输入单词”的典型语言学习活动。用户应该首先将句子的第一个单词拖到正确的位置并从那里继续前进。同时,我正在检查下一个单词是否在正确的位置。如果是这样,则该单词/项目会更改CSS类,并且不可拖动,并且具有不同的背景颜色。
要使CSS类发生更改,我克隆了可拖动单词列表,进行必要的更改,然后使用新的更新列表设置setState()。那是我遇到问题的时候。列表和组件会偶尔更新,似乎是随机的。当我尝试更新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
)
}
}
我在做什么错了?