【发布时间】:2019-02-18 06:16:05
【问题描述】:
ReactJS: 我正在尝试使用 Reactjs 呈现 <ul>。我创建了 2 个组件,一个用于个人 <li>,另一个用于 <ul>。我这样做是为了可以为每个事件单独处理事件/动画。现在我想将每个<li> 组件存储在<ul> 组件状态下的属性之一中。我希望在安装<ul> 组件之前完成此操作。 当<ul> 组件渲染时,所有<li> 组件也应该从<ul> 状态渲染。我该怎么做?
<ul> 状态的属性中有多个<li> 组件!根据客户在网络应用程序上的活动,它们应该是从服务器获取的。
我尝试通过创建一个 函数来调用 <ul> 组件的 setState,并使用 <li> 组件更新属性。 但是在 render() 中调用它会警告
Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
这是代码
//CartItemLI component is the <li>
class CartItemLI extends React.Component {
constructor(props)
{
super(props);
this.state = {
....
....
};
}
render()
{
return(
....
....
);
}
}
// Cart component is the <ul>
class Cart extends React.Component
{
constructor(props)
{
super(props);
this.state = {
....
....
//products property should store <CartItemLI />
products: []
}
}
//I tried invoking initItems() in the render(), but it gives the warning
initItems() {
for(var i = 0; i < this.state.numberOfItems; i++)
{
var products = this.state.products;
this.setState((prevState, props) => {
products: products.push(
<CartItemLI ....*props*.... />
)
})
}
}
render()
{
this.initItems();
// I want {this.state.products} from state
return (
<ul>
{this.state.products}
</ul>
)
}
}
【问题讨论】:
-
您没有解释为什么要将 li 存储在一个状态中。您可能有 XY 问题。
-
我希望 ul 是动态的,因为客户可以在 li 渲染后删除它。我还想为删除过程设置动画(我为此使用了anime.js)。我想也许将它们存储在 state 中并使用 setState 会更好,更容易解决这个问题。
-
您需要存储用于生成
(state.products) 的数据,而不是 本身。我认为存储 <CartItemLI>没有任何好处,它基本上是 createElement 对象。正如我所说,这是 XY 问题。考虑用对实际问题的解释而不是预期解决方案的问题来重新提出问题,这是错误的。