gpt4 book ai didi

javascript - 递增地 react 渲染 child

转载 作者:行者123 更新时间:2023-11-30 20:50:36 26 4
gpt4 key购买 nike

假设我有一个 React 元素 <Parent > 我需要渲染一个 <FooBar> 的数组

我的代码目前看起来像

Parent = React.createClass({

getChildren() {
var children = this.props.messages; // this could be 100's
return children.map((child) => {
return <FooBar c={child} />;
});
},

render() {
return (
<div>
{this.getChildren()}
</div>
);
}
});

当有 100 个 child 时,这真的很慢,因为 Parent等待所有 child 渲染。是否有一种解决方法可以逐步呈现子项,以便 Parent不必等待其所有子项呈现?

最佳答案

您可以一次获取一部分消息进行渲染,然后通过状态计数将更多子级的进一步更新排队。

使用 requestIdleCallbacksetTimeout 进行排队将允许您避免 React 的状态批处理拦截当前浏览器绘制,如果您使用 setState 这将是一个问题 直接来自 componentDidUpdate

这里有一些东西可以让你继续前进

const Parent = React.createClass({

numMessagesPerRender = 10

constructor(props) {
super(props)
this.state = {
renderedCount: 0
}
}

componentWillReceiveProps(props) {
// must check that if the messages change, and reset count if you do
// you may also need to do a deep equality of values if you mutate the message elsewhere
if (props.messages !== this.props.messages) {
this.setState({renderedCount: 0})
}
}

getChildren() {
// take only the current
const children = this.props.messages.slice(0, this.state.renderedCount);
return children.map(child => <FooBar c={child} />);
},

render() {
return (
<div>
{this.getChildren()}
</div>
);
}

renderMoreMessagesPlease() {
// you MUST include an escape condition as we are calling from `componentDidXYZ`
// if you dont your component will get stuck in a render loop and crash
if (this.state.renderedCount < this.props.messages.length) {
// queue up state change until the frame has been painted
// otherwise setState can halt rendering to do batching of state changes into a single
// if your browser doesnt support requestIdleCallback, setTimeout should do same trick
this.idleCallbackId = requestIdleCallback(() => this.setState(prevState => ({
renderedCount: prevState.renderedCount + this.numMessagesPerRender
})))
}
}

componentDidMount() {
this.renderMoreMessagesPlease()
}

componentDidUpdate() {
this.renderMoreMessagesPlease()
}

componentDidUnmount() {
// clean up so cant call setState on an unmounted component
if (this.idleCallbackId) {
window.cancelIdleCallback(this.idleCallbackId)
}
}

});

关于javascript - 递增地 react 渲染 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48228434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com