我正在尝试编写一个有时会重新排序它的孩子的组件,例如:
class Reorder extends React.PureComponent {
construnctor() {
this.state = {reorder: false}
}
render() {
if(this.state.reorder) {
return
<div>
<div key=0>{this.props.children[0]}</div>
<div key=1>{this.props.children[1]}</div>
</div>
} else {
return
<div>
<div key=1>{this.props.children[1]}</div>
<div key=0>{this.props.children[0]}</div>
</div>
}
}
}
class notifyOnMount extends React.PureComponent {
componentWillMount() {
console.log(`mounted ${this.props.name}`)
}
}
并使用它:
<Reorder reorder={shouldReorder}>
<notifyOnMount key="0" name="first" />
<notifyOnMount key="1" name="second" />
</Reorder>
但是在上面的示例中,每次shouldReorder更改时,我都会继续从两个组件重新渲染。我需要让孩子们安装好让他们正常行事。为什么他们会继续重新渲染?
答案 0 :(得分:0)
方法1 不使用条件渲染,而是使用css属性重新排序,如
class Reorder extends React.PureComponent {
constructor() {
this.state = {reorder: false}
}
render() {
const styles = {
display: flex,
flex-direction: this.state.reorder ? 'row': 'row-reverse'
}
return
<div style={styles}>
{this.props.children}
</div>
}
}
方法2
您可以做的另一件事是使用数组渲染子节点并在数组项上应用重新排序逻辑
class Parent extends React.Component {
state = {
data: [{name: 'first', key: 0}, {name: 'second', key: 1}]
}
reorderData = () => {
const data = [...this.state.data];
const newData = data.reverse();
this.setState({ data: newData })
}
componentDidUpdate(prevProps, prevState) {
if(this.state.shouldReorder !== prevState.shouldReorder) {
this.reorderData();
}
}
render() {
return <Reorder reorder={shouldReorder}>
{this.state.data.map((item, index) => <NotifyOnMount key={item.key} name={item.name} />)}
</Reorder>
}
}
和
class Reorder extends React.PureComponent {
render() {
return
<div>
{this.props.children}
</div>
}
}