未使用的JS函数含...others导致React组件props解构异常
问题:组件解构结果为何受未使用组件的影响?
我期望GoalComp控制台输出的props对象仅包含className成员,但实际它包含{className, id, ticket, request}这些成员。奇怪的是,只要把未使用的NullComp里的...others参数移除,props就仅保留className,和最初的预期一致。
带...others的测试代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Test</title> <script src="https://unpkg.com/react/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <div id="root"></div> <script type="text/babel"> function GoalComp({ id, ticket, request, ...props }) { console.log(props); return <div>Independent Retriever</div>; } </script> <script type="text/babel"> function NullComp({ timeRanges, ...others }) { return null; } </script> <script type="text/babel"> const { useState, useEffect } = React; const App = () => { return ( <GoalComp className="mt-10" id="1" ticket="IT-ABCD" request="Peace and Love" /> ); }; ReactDOM.render(<App />, document.querySelector("#root")); </script> </body> </html>
不带...others的测试代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Test</title> <script src="https://unpkg.com/react/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> </head> <body> <div id="root"></div> <script type="text/babel"> function GoalComp({ id, ticket, request, ...props }) { console.log(props); return <div>Independent Retriever</div>; } </script> <script type="text/babel"> function NullComp({ timeRanges }) { return null; } </script> <script type="text/babel"> const { useState, useEffect } = React; const App = () => { return ( <GoalComp className="mt-10" id="1" ticket="IT-ABCD" request="Peace and Love" /> ); }; ReactDOM.render(<App />, document.querySelector("#root")); </script> </body> </html>
原因解析
这是Babel生产环境下Tree Shaking(摇树优化)的特殊表现:
- 你使用的是React生产版本,Babel会自动移除未被使用的代码来压缩打包体积。
- 当
NullComp中存在...others剩余解构时,Babel无法判断这个组件是否会被动态调用(比如通过React.createElement传入任意props),因此不会对该组件执行Tree Shaking,反而会保留相关的解构逻辑。 - 这个未被优化的组件会干扰同编译上下文里
GoalComp的解构处理,导致GoalComp中声明的id、ticket、request没有被正确从props中剥离,最终props包含了所有传入的属性。 - 移除
NullComp里的...others后,Babel能确定这个未使用的组件没有依赖动态props,直接将整个组件Tree Shaking掉,不会干扰GoalComp的解构逻辑,所以props只保留预期的className。
内容的提问来源于stack exchange,提问作者Viewsonic
相关产品推荐
相关产品推荐

