我遇到了一个非常奇怪的问题,页面上只有一个组件没有被刷新,我就是不知道为什么。
这是该问题的简短视频:
https://i.gyazo.com/45e229b0867c37e48a18da7a55afb522.mp4
请注意当我单击确认时问题字符串如何变化(应该如此),但拖放窗口的卡片保持不变。它一直显示问题名称“yooo”和答案“abc,def”,而这仅对第一个问题有效。
我对 ReactJS 还是比较陌生,所以这里可能有一些我不熟悉的功能?据我所知 DragAndDrop 应该完全用下一个问题重新渲染。目前没有再次调用构造函数,它以某种方式保存了最后一个问题的数据。
此页面的渲染。DragAndDrop 在这里被调用。在 confirm() 中,currentQuestion 被设置为下一个问题。
return (
<div>
<h3>{currentQuestion.question}</h3>
<DragAndDrop
answers={currentQuestion.answers}
/>
<Button onClick={() => confirm()}>Confirm</Button>
</div>
);
整个 DragAndDrop.js 对不起代码墙,它与 Beautiful-DND 的示例代码几乎相同https://codesandbox.io/s/k260nyxq9v
/* eslint-disable no-console */
/* eslint-disable react/prop-types */
import React, { Component } from "react";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
// STYLING
const grid = 8;
const getItemStyle = (isDragging, draggableStyle) => ({
// some basic styles to make the items look a bit nicer
userSelect: "none",
padding: grid * 2,
margin: `0 0 ${grid}px 0`,
// change background colour if dragging
background: isDragging ? "cyan" : "white",
// styles we need to apply on draggables
...draggableStyle,
});
const getListStyle = (isDraggingOver) => ({
background: isDraggingOver ? "lightblue" : "lightgrey",
padding: grid,
width: "100%",
});
// a little function to help us with reordering the result
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
export default class DragAndDrop extends Component {
constructor(props) {
super(props);
this.state = {
items: props.answers,
};
this.onDragEnd = this.onDragEnd.bind(this);
console.log("Answers & items");
console.log(this.props.answers);
console.log(this.state.items);
}
onDragEnd(result) {
// dropped outside list
if (!result.destination) {
return;
}
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
this.setState({
items,
});
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
style={getListStyle(snapshot.isDraggingOver)}
>
{this.state.items.map((item, index) => (
<Draggable
key={item.id}
draggableId={item.id.toString()}
index={index}
>
{(provided, snapshot) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={getItemStyle(
snapshot.isDragging,
provided.draggableProps.style
)}
>
{
item.answer +
" index: " +
index +
" ordering:" +
item.ordering /*CONTENT OF CARD*/
}
</div>
)}
</Draggable>
))}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
);
}
}