如下面的代码所示,App组件有一个状态。此状态的属性通过props传递给子组件。但是,一旦App组件中的状态发生更改,则不会更新可排序组件中的子组件。但是这个可排序容器之外的子组件会照常更新(重新呈现)。
如何实现在每个状态更改时呈现这些可排序的子组件?
代码如下(简化):
App.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>)
}
}页面加载时的外观:


..。状态更新后:


发布于 2019-08-06 03:24:03
看起来像是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的状态发生变化时要做什么(如果有的话)。
https://stackoverflow.com/questions/57364819
复制相似问题