我在我的反应应用程序中有3个组件
之前我使用状态
渲染它们state = {
one: true,
two: false,
three: false
}
通过将其状态设置为true并将所有其他状态设置为false来呈现我想要的那个
并渲染它们
<div>
{
this.state.one &&
<Start
switchDisplay={ this.switchDisplay }
quizname={ quizname }
author={ author }
/>
}
{ this.state.two &&
<Playground
{...this.state.currentQuestion}
onclick={this.nextQuestion}
/>
}
{
this.state.three &&
<Score nominator={this.result} denominator={entry.length}/>
}
</div>
(暂不考虑当下的道具)
后来我使用了第三方软件包
https://www.npmjs.com/package/react-display-name
现在重构了一点点后。
我只有一个将组件作为其值的状态
如果我需要在组件之间切换,我只需更改它的状态
并传递道具我使用了这个第三方包
获取当前组件名称和一些条件逻辑以传递道具
我的问题是哪种方法更好
让所有组件都处于状态 并将值设置为true,将所有其他值设置为false。
或
将组件的一个状态直接作为其值传入。
并使用“第三方包”获取当前呈现的组件的显示名称,并使用组件名称传入道具。
更多州或一个额外的包裹?
答案 0 :(得分:3)
减少协调状态变化所做的工作始终是一种成功的方法。因此,更好的方法是将组件的一个状态作为其值直接传入。
如果每次只显示3个组件中的一个,则可能不需要外部库。
constructor()
const state = {
display: 'start',
};
this.state = state;
使用对象键作为可能的状态值连接所有3个组件的查找对象
const gameComponentRegistry = {
'start': Start,
'playground': Playground,
'score': Score,
}
export default gameComponentRegistry;
在render()
中,导入和查找要在gameComponentRegistry
const component = gameComponentRegistry[this.state.display];
const props = {}; // makeup props
<div>
{ <component ...props /> }
</div>