Javascript React 功能组件默认道具与默认参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47774695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React functional component default props vs default parameters
提问by Iago Dahlem
In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameterson the function definition, examples:
在 React功能组件中,这是设置默认道具、使用Component.defaultProps或使用函数定义上的默认参数的更好方法,示例:
Default props:
默认道具:
const Component = ({ prop1, prop2 }) => (
<div></div>
)
Component.defaultProps = {
prop1: false,
prop2: 'My Prop',
}
Default parameters:
默认参数:
const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (
<div></div>
)
回答by Abdennour TOUMI
In general (ES6), the second way is better.
一般来说(ES6),第二种方式更好。
In specific (in React context), the first is better since it is a main phase in the component lifecycle, namely, the initialization phase.
具体来说(在 React 上下文中),第一个更好,因为它是组件生命周期中的一个主要阶段,即初始化阶段。
Remember, ReactJS was invented before ES6.
请记住,ReactJS 是在 ES6 之前发明的。
回答by Tom
defaultPropson functional components will eventually be deprecated (as per Dan Abramov, one of the core team), so for future-proofing it's worth using default parameters.
defaultProps在功能组件上最终将被弃用(根据核心团队之一丹·阿布拉莫夫的说法),因此为了面向未来,值得使用默认参数。
回答by Zen
Shameless Plug here, I'm the author of with-default-props.
无耻的插件在这里,我是 with-default-props 的作者。
If you are a TypeScript user, with-default-propsmight help you, which uses higher order function to provide correct component definition with defaultProps given.
如果您是 TypeScript 用户,with-default-props可能会对您有所帮助,它使用高阶函数来提供正确的组件定义,并提供给定的 defaultProps。
Eg.
例如。
import { withDefaultProps } from 'with-default-props'
type Props = {
text: string;
onClick: () => void;
};
function Component(props: Props) {
return <div onClick={props.onClick}>{props.text}</div>;
}
// `onClick` is optional now.
const Wrapped = withDefaultProps(Component, { onClick: () => {} })
function App1() {
// ?
return <Wrapped text="hello"></Wrapped>
}
function App2() {
// ?
return <Wrapped text="hello" onClick={() => {}}></Wrapped>
}
function App3() {
// ?
// Error: `text` is missing!
return <Wrapped onClick={() => {}}></Wrapped>
}
回答by SayJeyHi
Even maybe you ask, why not use sth like below code with props || valueinstead of defaultProps:
甚至你可能会问,为什么不使用下面的代码props || value代替defaultProps:
class SomeComponent extends React.Component {
render() {
let data = this.props.data || {foo: 'bar'}
return (
<div>rendered</div>
)
}
}
// SomeComponent.defaultProps = {
// data: {foo: 'bar'}
// };
ReactDOM.render(
<AddAddressComponent />,
document.getElementById('app')
)
But remember defaultPropsmake code more readable , specially if you have more propsand controlling them with ||operator could make your code looks ugly
但是请记住defaultProps使代码更具可读性,特别是如果您有更多代码props并且使用||运算符控制它们可能会使您的代码看起来很丑陋
回答by Jkarttunen
First one can cause some hard-to-debug performance problems, especially if you are using redux.
第一个可能会导致一些难以调试的性能问题,尤其是在您使用 redux 时。
If you are using objects or lists or functions, those will be new objects on every render. This can be bad if you have complex components that check the component idenitity to see if rerendering should be done.
如果您正在使用对象、列表或函数,那么这些将是每次渲染时的新对象。如果您有复杂的组件来检查组件身份以查看是否应该进行重新渲染,这可能会很糟糕。
const Component = ({ prop1 = {my:'prop'}, prop2 = ['My Prop'], prop3 = ()=>{} }) => {(
<div>Hello</div>
)}
Now that works fine, but if you have more complex component and state, such as react-redux connected components with database connection and/or react useffect hooks, and component state, this can cause a lot of rerending.
现在工作正常,但是如果您有更复杂的组件和状态,例如带有数据库连接和/或 react useffect 钩子的 react-redux 连接组件,以及组件状态,这可能会导致大量重新渲染。
It is generally better practice to have default prop objects created separately, eg.
单独创建默认道具对象通常是更好的做法,例如。
const Component = ({prop1, prop2, prop3 }) => (
<div>Hello</div>
)
Component.defaultProps = {
prop1: {my:'prop'},
prop2: ['My Prop'],
prop3: ()=>{}
}
or
或者
const defaultProps = {
prop1: {my:'prop'},
prop2: ['My Prop'],
prop3: ()=>{}
}
const Component = ({
prop1 = defaultProps.prop1,
prop2 = defaultProps.prop2
prop3 = defaultProps.prop3
}) => (
<div>Hello</div>
)
回答by Ali Kleit
You may want to try this in case you have some parameter you want to set its default value
如果您有一些要设置其默认值的参数,您可能想尝试一下
const MyComponent = (props) => {
const {title, status} = props
const safeTitle = title || 'My default title'
// in case its a number (status may be 0):
const safeStatus = status === undefined ? 1 : status
}

