有没有办法在反应中传递一组道具?
Is there a way to pass a group of props in react?
我实际使用的方式很好,但我的道具不断增长,我想知道我是否可以将它们组合成一个状态并将其传递给 child,这是我的代码:
<Panel
uniqueIDs={uniqueIDs}
userID={userID}
loading={loading}
premium={premium}
percent={percent}
total={total}
until={until}
user={user}
done={done}
/>
在渲染之后我定义了这些变量:
let { loading, empty, total, uniqueIDs, slice, percent, until, ok,
user, premium, data, keys, done, userID } = this.state;
我可以只发送 this.state
变量吗?我做了一些研究,但没有找到解决问题的方法,我知道我可以使用 third-party 库来管理状态,但我尽量保持简单。
你可以为你发送的道具制作一个对象,并可以使用传播运算符
let props = {
uniqueIDs : uniqueIDs,
userID:userID,
loading:loading,
premium:premium
}
<Panel {...props} />
在面板组件中,您可以使用 this.props.uniqueIDs 等。
是的,您绝对可以将整个 state-variable 作为多个属性传递到 child-component 中
<Child {...this.state}/>
这完全可以接受。
如果你所在的州是{id: 1, name: 2}
您仍然可以访问 child-component 中的道具,因为
props.id or this.props.id
props.name or this.props.name
请注意,您应该了解组件 re-rendering。如果您对 parent-component 中的状态进行多次更新,这也会导致您的子组件也 re-render 很多,这可能会出现性能问题。
要解决此问题,请确保对 class-components 使用 componentDidUpdate()
和对功能组件使用 react-hooks
等方法。这些可以帮助控制 re-rendering.
的流量
我实际使用的方式很好,但我的道具不断增长,我想知道我是否可以将它们组合成一个状态并将其传递给 child,这是我的代码:
<Panel
uniqueIDs={uniqueIDs}
userID={userID}
loading={loading}
premium={premium}
percent={percent}
total={total}
until={until}
user={user}
done={done}
/>
在渲染之后我定义了这些变量:
let { loading, empty, total, uniqueIDs, slice, percent, until, ok, user, premium, data, keys, done, userID } = this.state;
我可以只发送 this.state
变量吗?我做了一些研究,但没有找到解决问题的方法,我知道我可以使用 third-party 库来管理状态,但我尽量保持简单。
你可以为你发送的道具制作一个对象,并可以使用传播运算符
let props = {
uniqueIDs : uniqueIDs,
userID:userID,
loading:loading,
premium:premium
}
<Panel {...props} />
在面板组件中,您可以使用 this.props.uniqueIDs 等。
是的,您绝对可以将整个 state-variable 作为多个属性传递到 child-component 中
<Child {...this.state}/>
这完全可以接受。
如果你所在的州是{id: 1, name: 2}
您仍然可以访问 child-component 中的道具,因为
props.id or this.props.id
props.name or this.props.name
请注意,您应该了解组件 re-rendering。如果您对 parent-component 中的状态进行多次更新,这也会导致您的子组件也 re-render 很多,这可能会出现性能问题。
要解决此问题,请确保对 class-components 使用 componentDidUpdate()
和对功能组件使用 react-hooks
等方法。这些可以帮助控制 re-rendering.