如下面的代码所示,App组件有一个状态。该状态的属性通过 props 传递给子组件。 但是,一旦 App 组件中的状态发生变化,Sortable 组件内的 Child 组件就不会更新。但是此可排序容器之外的子组件会照常更新(重新渲染)。
如何实现这些可排序的子组件在每次状态更改时呈现?
这是代码(简化):
应用程序.js:
import Sortable from 'react-sortablejs';
import Child from './Child';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text1: "Text1",
text2: "Text2"
}
}
render() {
return (
<div className="App">
<Sortable>
<Child text={this.state.text1} />
<Child text={this.state.text2} />
</Sortable>
<Child text={this.state.text1} />
</div>
);
}
}
Child.js: 从 'react' 导入 React;
export default class Child extends React.Component {
constructor(props) {
super(props);
}
render() {
return (<p>{this.props.text}</p>)
}
}
页面加载后的样子:
...状态更新后:
最佳答案
看起来 Sortable
组件覆盖了 shouldComponentUpdate
here :
shouldComponentUpdate(nextProps) {
// If onChange is null, it is an UnControlled component
// Don't let React re-render it by setting return to false
if (!nextProps.onChange) {
return false;
}
return true;
}
基本上,它被设置为仅在存在 onChange
处理程序时才更改。您需要传递一个类似的方法来确定当 App
的状态发生变化时要做什么(如果有的话)。
关于javascript - 如何维护Sortable容器的子组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364819/